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
2009-11-05 09:05:56
no regex in cocoa-touch
Kenny Winker
2009-11-05 11:37:26
+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
2009-11-05 10:04:48
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
2010-04-12 13:31:21