小智 27

这是使用现代inet_pton的类别,它将为有效的IPv4或IPv6字符串返回YES.

    #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
Run Code Online (Sandbox Code Playgroud)

  • 为了将来参考,成功== 1?TRUE:不需要FALSE.一个简单的成功== 1会起作用. (4认同)

Ale*_*lds 5

这是一种可能也有帮助的替代方法.假设您有一个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]);
}
Run Code Online (Sandbox Code Playgroud)

如果需要该级别的验证,您可以修改if条件块以遵循RFC 1918准则.