Abdullah Umer
Abdullah Umer

Reputation: 4634

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?

Upvotes: 1

Views: 2006

Answers (2)

gmogames
gmogames

Reputation: 3081

** 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

Upvotes: 6

Dan
Dan

Reputation: 5173

No - it's not possible to programmatically retrieve your external (global) IP address strictly using code. Regarding using a service to view your external IP I would look into what you're eluding to: parsing or scraping the HTML returned from the two sites you mentioned or also CheckIP.

[NSData dataWithContentsOfURL:url]

An example of what CheckIP returns is below which is pretty simple and could easily be grabbed using RegEx

<html>
 <head>
  <title>
   Current IP Check
  </title>
 </head>
 <body>
  Current IP Address: 108.66.182.170
 </body>
</html>

EDIT: using the URL from @gmogames' answer all you would have to do is the following to get the data into a string:

NSURL *theURL = [[NSURL alloc] initWithString:@"http://api-sth01.exip.org/?call=ip"];
NSString* myIP = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:theURL]
                                     encoding:NSUTF8StringEncoding];

Upvotes: 0

Related Questions