开发者

How to validate an IP address with regular expression in Objective-C?

How to val开发者_JAVA技巧idate an IP address in Objective-C?


Here's a category using the modern inet_pton which will return YES for a valid IPv4 or IPv6 string.

    #include <arpa/inet.h>

    @implementation NSString (IPValidation)

    - (BOOL)isValidIPAddress
    {
        const char *utf8 = [self UTF8String];
        int success;

        struct in_addr dst;
        success = inet_pton(AF_INET, utf8, &dst);
        if (success != 1) {
            struct in6_addr dst6;
            success = inet_pton(AF_INET6, utf8, &dst6);
        }

        return success == 1;
    }

    @end


Here's an alternative approach that might also help. Let's assume you have an NSString* that contains your IP address, called ipAddressStr, of the format a.b.c.d:

int ipQuads[4];
const char *ipAddress = [ipAddressStr cStringUsingEncoding:NSUTF8StringEncoding];

sscanf(ipAddress, "%d.%d.%d.%d", &ipQuads[0], &ipQuads[1], &ipQuads[2], &ipQuads[3]);

@try {
   for (int quad = 0; quad < 4; quad++) {
      if ((ipQuads[quad] < 0) || (ipQuads[quad] > 255)) {
         NSException *ipException = [NSException
            exceptionWithName:@"IPNotFormattedCorrectly"
            reason:@"IP range is invalid"
            userInfo:nil];
         @throw ipException;
      }
   }
}
@catch (NSException *exc) {
   NSLog(@"ERROR: %@", [exc reason]);
}

You could modify the if conditional block to follow RFC 1918 guidelines, if you need that level of validation.


Swift edition:

func isIPAddressValid(ip: String) -> Bool {
    guard let utf8Str = (ip as NSString).utf8String else {
        return false
    }

    let utf8:UnsafePointer<Int8> = UnsafePointer(utf8Str)
    var success: Int32

    var dst: in_addr = in_addr()
    success = inet_pton(AF_INET, utf8, &dst)
    if (success != 1) {
        var dst6: in6_addr? = in6_addr()
        success = inet_pton(AF_INET6, utf8, &dst6);
    }

    return success == 1
}


A trick you can do is test the return of the inet_aton BSD call like this:

#include <arpa/inet.h>

- (BOOL)isIp:(NSString*)string{
    struct in_addr pin;
    int success = inet_aton([string UTF8String],&pin);
    if (success == 1) return TRUE;
    return FALSE;
}

Be aware however that this validates the string if it contains a ip address in any format, it is not restricted to the dotted format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜