How to get the public IP address of the device

前端 未结 9 570
陌清茗
陌清茗 2020-12-29 10:32

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

9条回答
  •  长发绾君心
    2020-12-29 10:59

    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];
    

提交回复
热议问题