iPhone SDK:如何检查用户输入的IP是否有效?

时间:2011-03-01 12:31:18

标签: iphone objective-c ip-address nsurlrequest

我的iPhone应用程序包含对服务器的多个http请求。用户可以输入服务器的IP地址,这样您就可以将该应用与您自己的私人服务器结合使用。

在发出请求之前,我总是检查输入的IP地址是否有效,我是这样做的:

-(BOOL)urlExists {

NSString *url = [NSString stringWithFormat:@"%@", ipAddress];
NSURLRequest *myRequest1 = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:myRequest1 returningResponse:&response error:&error];
if ([response statusCode] == 404){
    return NO;

}
else{
    return YES;
}

[url release];
[response release];
[error release];
[myRequest1 release];

}

只要输入的地址如下所示,这就完美无缺:xx.xx.xxx.xxx 但是如果您尝试输入类似“1234”或“test”的内容,则上面显示的代码不起作用。所以我不得不检查输入的地址是否“看起来”像一个IP地址,我不知道如何做到这一点。

非常感谢任何建议!

2 个答案:

答案 0 :(得分:8)

您可以通过以下方法检查网址有效期:

- (BOOL) validateUrl: (NSString *) candidate {
    NSString *urlRegEx =
    @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate];
}

答案 1 :(得分:2)

-(BOOL)isIPAddressValid:(NSString*)ipAddress{

ipAddress = [ipAddress stringByReplacingOccurrencesOfString:@"https://" withString:@""];
ipAddress = [ipAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];

NSArray *components = [ipAddress componentsSeparatedByString:@"."];
if (components.count != 4) {
    return NO;
}
NSCharacterSet *unwantedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
if ([ipAddress rangeOfCharacterFromSet:unwantedCharacters].location != NSNotFound){
    return NO;
}
for (NSString *string in components) {
    if ((string.length < 1) || (string.length > 3 )) {
        return NO;
    }
    if (string.intValue > 255) {
        return NO;
    }
}
if  ([[components objectAtIndex:0]intValue]==0){
    return NO;
}
return YES;

}