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 ...
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 ...
I find both Andrei and Tarek's answers helpful. Both are relying a web URL to query the "public IP" of the iOS/OS X device.
However, there is an issue with this approach in some part of the world where URL such as "http://www.dyndns.org/cgi-bin/check_ip.cgi" is censored as in andrei's answer:
In this case, we will need to use an "uncensored" URL within the region such as http://1212.ip138.com/ic.asp
Note that the web URL could use a different HTML and encoding than what Andrei's answer could parse - in the URL above, some very gentle changes can fix it by using kCFStringEncodingGB_18030_2000 for http://1212.ip138.com/ic.asp
I use ipify and with no complaints.
I have used ALSystemUtilities in the past. You basically have to make a call externally to find this out.
Source from ALSystemUtilities
You have to query an external server to find out the public IP. Either set up your own server (1 line of php code) or use one of the many available ones which return the IP as plain text or json upon http query. Like for example http://myipdoc.com/ip.php .
It's as simple as this:
For those of us using Swift, here's my translation of Andrei's answer with the addition of NSURLSession to run it in the background. To check the network, I use Reachability.swift. Also, remember to add dyndns.org to
NSExceptionDomains
forNSAppTransportSecurity
in yourinfo.plist
.