How to get the public IP address of the device

Damien Romito picture Damien Romito · Dec 30, 2014 · Viewed 14.6k times · Source

I found this sample code to get all local IP addresses, but I don't find an easy solution to get the public IP.

A legacy class from Apple allowed to do that ... but it's legacy ...

Answer

Tarek picture Tarek · Jul 1, 2016

It's as simple as this:

NSString *publicIP = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://icanhazip.com/"] encoding:NSUTF8StringEncoding error:nil];
publicIP = [publicIP stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; // IP comes with a newline for some reason