Search This Blog

Monday, 15 June 2015

How to get IP Address in iOS

Long time .... sorry for being not available since long. Life you know.... hahahaha !

So, i was looking for some solution to find IP Address in iOS , and to be very frank , i found codes that are useless now with iOS 7, 8 and 9 in market.

I tried NSHost also, but not so appealing to me either.

Here is something i found from anonymous developer, he shared it as a block of code, i created a function, which you my fellow developers, can copy and paste and it will return you the IP.

Simple as it is.....i still remember my promise...Pure code no talks ;)


FUNCTION TO GET IP IN RESPONSE:

-(NSString *) getIPforDevice{
    NSUInteger  an_Integer;
    NSArray * ipItemsArray;
    NSString *externalIP;
    
    NSURL *iPURL = [NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"];
    
    if (iPURL) {
        NSError *error = nil;
        NSString *theIpHtml = [NSString stringWithContentsOfURL:iPURL
                                                       encoding:NSUTF8StringEncoding
                                                          error:&error];
        if (!error) {
            NSScanner *theScanner;
            NSString *text = nil;
            
            theScanner = [NSScanner scannerWithString:theIpHtml];
            
            while ([theScanner isAtEnd] == NO) {
                
                // find start of tag
                [theScanner scanUpToString:@"<" intoString:NULL] ;
                
                // find end of tag
                [theScanner scanUpToString:@">" intoString:&text] ;
                
                // replace the found tag with a space
                //(you can filter multi-spaces out later if you wish)
                theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
                             [ NSString stringWithFormat:@"%@>", text]
                                                                 withString:@" "] ;
                ipItemsArray =[theIpHtml  componentsSeparatedByString:@" "];
                an_Integer=[ipItemsArray indexOfObject:@"Address:"];
                
                externalIP =[ipItemsArray objectAtIndex:  ++an_Integer];
                
                
                
            } 
            
            
            NSLog(@"%@",externalIP);
        } else {
            NSLog(@"Oops... g %d, %@"
                  [error code], 
                  [error localizedDescription]);
        }
    }
    return externalIP;

}


Always feel free to ask any queries....

Happy Programming...

CHAO!

No comments:

Post a Comment