Abdullah Umer Abdullah Umer - 5 months ago 26
Objective-C Question

Global IP address programmatically

I need to get the Global IP address in my iOS app.

I searched but couldn't find any posts regarding getting Global IP address. Most of them were for getting local IP address.

I tried this code: How to find IP Address of iPhone. But this returns the local IP address.

For my app, I need to get the IP address as shown by the websites e.g.:

http://myipaddress.com/show-my-ip-address/ and
http://whatismyipaddress.com/

Is it possible to get the Global IP address in iOS app programmatically? One option is to use web services like above but response from these websites will be HTML. Is there any free web service which would return a simple JSON or XML?

Answer

** EDIT 06/29/16: ** I've updated the URL of the API because the older one does not work anymore.

You can use: https://api.ipify.org/?format=text

It's a plain string. You can get the responseObject and store and use it in your app. I recommend AFNetworking, it's a simple call and return and you do not need JSON or xml.

NSURL *URL = [NSURL URLWithString:@"http://api-sth01.exip.org/"];
NSString *URLPath = @"?call=ip";

// Start Connection
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:URL];
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:URLPath parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // SAVE responseObject to your app

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // Failed
    NSLog(@"error: %@",  operation.responseString);

}];

[operation start];

But if you want JSON, you can use: https://api.ipify.org/?format=json