如何在Objective-C中验证IP地址?
答案 0 :(得分: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
答案 1 :(得分:5)
这是一种可能也有帮助的替代方法。假设您有一个NSString*
,其中包含您的IP地址,名为ipAddressStr
,格式为 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]);
}
如果您需要该级别的验证,则可以修改if
条件块以遵循RFC 1918指南。
答案 2 :(得分:3)
斯威夫特版:
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
}
答案 3 :(得分:1)
你可以做的一个技巧是测试inet_aton BSD调用的返回,如下所示:
#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;
}
请注意,如果字符串包含任何格式的IP地址,则会验证字符串,但不限于点缀格式。