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 ... bu
I use ipify and with no complaints.
NSURL *url = [NSURL URLWithString:@"https://api.ipify.org/"];
NSString *ipAddress = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"My public IP address is: %@", ipAddress);
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:
NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
encoding:NSUTF8StringEncoding
error:&error];
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
NSURL* externalIPCheckURL = [NSURL URLWithString: @"http://1212.ip138.com/ic.asp"];
encoding:NSUTF8StringEncoding error:nil];
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *theIpHtml = [NSString stringWithContentsOfURL: externalIPCheckURL
encoding: encoding
error: &error];
Thanks @Tarek for his answer
Here, code in Swift 4 version
func getPublicIPAddress() -> String {
var publicIP = ""
do {
try publicIP = String(contentsOf: URL(string: "https://www.bluewindsolution.com/tools/getpublicip.php")!, encoding: String.Encoding.utf8)
publicIP = publicIP.trimmingCharacters(in: CharacterSet.whitespaces)
}
catch {
print("Error: \(error)")
}
return publicIP
}
NOTE1: To get public IP address, we must have external site to return public IP. The website I use is business company website, so, it will be their until the business gone.
NOTE2: You can made some site by yourself, however, Apple require HTTPS site to be able to use this function.