IPhone SDK: How to check if the IP address is really entered by the user?

My iPhone application includes several HTTP requests to the server. The IP address of the server can be entered by the user, so you can use the application in combination with your own personal server.

Before making requests, I always check to see if the IP address I entered is valid, and I do it as follows:

-(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 fine, as long as the address you enter 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. Therefore, for some reason I need to check whether the entered address looks like an “IP address”, and I do not know how to do this.

Any suggestions are welcome!

+3
2

URL :

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

}

+1

Source: https://habr.com/ru/post/1795480/


All Articles