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

How to validate an IP address with regular expression 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}