iPhone SDK: How to check if IP entered by user is valid?

こ雲淡風輕ζ 提交于 2019-12-13 14:25:56

问题


My iPhone application includes several http requests to a server. The server's IP address can be entered by the user so you can use the app in combination with your own private server.

Before making the requests I always check whether or not the IP address entered is valid and I do it like this:

-(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];

}

This works perfectly as long as the entered address looks something like this: xx.xx.xxx.xxx But if you try to enter something like this, "1234" or "test", the code shown above does not work. So I somehow have to check if the entered address "looks" like an IP-address and I have no idea how to do this.

Any suggestions are greatly appreciated!


回答1:


You can check url validity from below method :

- (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];
}



回答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;

}



来源:https://stackoverflow.com/questions/5154545/iphone-sdk-how-to-check-if-ip-entered-by-user-is-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!