Zeebok Zeebok - 25 days ago 5
iOS Question

How to check private/local IP address by using regular expression

Hope all of you will be fine. I am building an IOS application in which I warn the user if they typed a private/local IP address in text-field.
I have searched on internet and found it done in the Android app using regular expression:
Java: (127.0.0.1)|(192.168.$) | (172.1[6-9].$) | (172.2[0-9].$) | (172.3[0-1].$) | (10.*$)

I want the same regular expression for IOS application but I don't know how to code it.
I searched on internet and found
Private IP Address Identifier in Regular Expression
but i could not understand it. I just know some objective-c. Can some one help me in this regard please.

Ok guys finally I think I have solved the problem by following code.



-(void)CheckIP
{
NSError *error = NULL;
NSString *pattern = @"(127.0.0.1)|(192.168.$)|(172.1[6-9].$)|(172.2[0-9].$)|(172.3[0-1].$)|(10.*$)"; // "[a-zA-Z]+[,]\\s*([A-Z]{2})";
NSString *string = self.tfExternalHost.text;
NSRange range = NSMakeRange(0, string.length);
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:NSMatchingProgress range:range];
NSLog(@" Found Match %@", matches);
}





Suggest me if the above code can be improved.

Answer

Guys i have solved the problem. Enjoy code.

-(BOOL)CheckIPAddress
{
    // this code is to check either user entered local/private ip-address
    NSError *error = NULL;    
    NSString *pattern = @"((127\.)|(10\.)|(172\.1[6-9]\.)|(172\.2[0-9]\.)|(172\.3[0-1]\.)|(192\.168\.))";
    NSString *string = self.tfExternalHost.text;
    NSRange range = NSMakeRange(0, string.length);
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    NSArray *matches = [regex matchesInString:string options:NSMatchingProgress range:range];
    if (matches.count>0) {
        UIAlertView *simpleAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"Please provide valid external IP address.", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [simpleAlert show];
        return true;
    }
    return false;
}