tags:

views:

784

answers:

4

How to validate an IP address in objective C.

A: 

Objective-C does not include a builtin regexp library. Even if it did, using regexp's against something like an IP address is much slower than just using netmasks and bitwise oeprators to see if IPs are within the ranges you want.

Louis Gerbarg
A: 

"RegExp for validating the format of IP Addresses"

Boris Modylevsky
no regex in cocoa-touch
Kenny Winker
+4  A: 

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:

unsigned char 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.

Alex Reynolds
A: 

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.

valexa