How to get the public IP address of the device

前端 未结 9 542
陌清茗
陌清茗 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:57

    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);
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2020-12-29 11:03

    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.

    0 讨论(0)
提交回复
热议问题