如何在Objective-C中验证IP地址?
这是使用现代inet_pton的类别,它将为有效的IPv4或IPv6字符串返回YES.
#include@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
这是一种可能也有帮助的替代方法.假设您有一个NSString*
包含您的IP地址,称为abcdipAddressStr
格式:
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]); }
如果需要该级别的验证,您可以修改if
条件块以遵循RFC 1918准则.