如何获取设备的公共IP地址

Dam*_*ito 9 public objective-c ip-address ios

我找到了这个示例代码来获取所有本地IP地址,但我找不到一个简单的解决方案来获取公共IP.

来自Apple 的传统课程允许这样做...但它的遗产......

Tar*_*rek 17

这很简单:

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
Run Code Online (Sandbox Code Playgroud)

  • 哈哈哈.我不知道我多么信任域名为"icanhazip.com"的网站的长寿.:) (5认同)
  • `icanhazip.com`实际上是Backspace员工真正知名的服务,现在已经运行了很多年(至少7年).有关详细信息,请查看以下链接:[icanhazip FAQ](https://major.io/icanhazip-com-faq/) (4认同)

And*_*rei 10

我过去使用过ALSystemUtilities.你基本上必须在外部打电话才能找到它.

+ (NSString *)externalIPAddress {
    // Check if we have an internet connection then try to get the External IP Address
    if (![self connectedViaWiFi] && ![self connectedVia3G]) {
        // Not connected to anything, return nil
        return nil;
    }

    // Get the external IP Address based on dynsns.org
    NSError *error = nil;
    NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
    if (!error) {
        NSUInteger  an_Integer;
        NSArray *ipItemsArray;
        NSString *externalIP;
        NSScanner *theScanner;
        NSString *text = nil;

        theScanner = [NSScanner scannerWithString:theIpHtml];

        while ([theScanner isAtEnd] == NO) {

            // find start of tag
            [theScanner scanUpToString:@"<" intoString:NULL] ;

            // find end of tag
            [theScanner scanUpToString:@">" intoString:&text] ;

            // replace the found tag with a space
            //(you can filter multi-spaces out later if you wish)
            theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
                         [ NSString stringWithFormat:@"%@>", text]
                                                             withString:@" "] ;
            ipItemsArray = [theIpHtml  componentsSeparatedByString:@" "];
            an_Integer = [ipItemsArray indexOfObject:@"Address:"];
            externalIP =[ipItemsArray objectAtIndex:++an_Integer];
        }
        // Check that you get something back
        if (externalIP == nil || externalIP.length <= 0) {
            // Error, no address found
            return nil;
        }
        // Return External IP
        return externalIP;
    } else {
        // Error, no address found
        return nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

来自ALSystemUtilities的资源

  • 如果"公共IP"是指"互联网将看到我来自的IP地址",那么如果不询问互联网的某些部分就无法知道.您的设备上不会出现NAT; 它发生在网络上.请注意,根据您的路由方式,不同的设备可能会将您视为具有不同的IP(包括某些人可能会将您视为具有IPv4地址而其他人看到您使用IPv6地址)."互联网"只是一个特定的网络; 您可以在具有不同IP映射的许多不同网络之间进行路由. (8认同)

Sru*_*Suk 7

感谢@Tarek 的回答

这里是 Swift 4 版本的代码

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
}
Run Code Online (Sandbox Code Playgroud)

注意1:要获取公共IP地址,我们必须有外部站点返回公共IP。我使用的网站是商业公司的网站,所以,直到生意消失为止,这将是他们的网站。

注意2:您可以自己创建一些站点,但是Apple需要HTTPS站点才能使用此功能。