【问题标题】:How to get the external ip in Objective-C如何在 Objective-C 中获取外部 ip
【发布时间】:2011-03-27 16:39:51
【问题描述】:

我找了一些代码来帮助我获取 iPhone 连接的 ip。

我找到了这个:

- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }

            temp_addr = temp_addr->ifa_next;
        }
    }

    // Free memory
    freeifaddrs(interfaces);

    return address;
}

但问题是他给我这个ip 10.0.0.1

如何获取外部ip?

【问题讨论】:

  • 您希望得到什么样的 IP 地址?该设备可能正在通过 WiFi 或 3G 网络等,因此您不可能检索任何形式的有意义的“外部”IP 地址。
  • Middaparka 是对的 - 从设备的角度来看,10.0.0.1 它的外部 IP 地址。

标签: iphone objective-c cocoa-touch ios


【解决方案1】:

从代码中获取您的互联网 IP 地址的最简单方法是使用 NSURLConnection

对于您可以使用的 URL: http://www.whatismyip.com/m/mobile.asp 或者 http://checkip.dyndns.com/

只需解析返回数据,您就有了您的外部 IP 地址。

【讨论】:

  • 我喜欢。对于 prod 应用程序来说不是很多,但对于调试来说非常好。 +1
  • 除非你有 1000 万的 DAU 并且每次发布都调用这个,否则你真的要在 WhatIsMyIP.com 上花费很多钱来购买可能是本地功能的东西。 :o
【解决方案2】:

看看我的第二个答案here中的例子。

简而言之,它使用 *http://www.dyndns.org/cgi-bin/check_ip.cg*i 来获取外部 IP

【讨论】:

    【解决方案3】:

    查看 Apple 的 PortMapper,完全符合您的要求。

    从 iOS7 开始,这无关紧要。

    【讨论】:

    • PortMapper 用于“运行时要求:Mac OS X 10.5”
    • 我将它用于我的 iPhone 应用程序。
    • 我记得没什么大不了的。完美运行,3G 或 Wifi。
    • 绝对没有什么要补充的。 PortMapper 完美地完成了这项工作。故事结局。如果您愿意,请投反对票。
    • 在 iOS 7 上给我的公共 ip 地址为 null
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 2012-05-08
    • 2021-11-20
    • 2012-05-06
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    相关资源
    最近更新 更多