【问题标题】:How do I query the iPhone's current IP address?如何查询 iPhone 当前的 IP 地址?
【发布时间】:2010-09-20 14:27:56
【问题描述】:

如何查询iPhone当前的IP地址?

【问题讨论】:

    标签: iphone networking


    【解决方案1】:

    如果您想要external IP 地址(用于从本地网络外部连接的地址),您需要查询外部网络上的服务器。快速搜索得到以下结果:http://checkip.dyndns.orghttp://www.whatismyip.com。使用例如加载页面非常简单。

    [NSData dataWithContentsOfURL:url]

    并进行一些字符串操作以检索 IP 地址。

    如果您想要内部 IP 地址(例如由 DHCP 分配给您的设备的地址),您通常可以做的是解析设备的主机名,即

    
    /*
    Returns the local IP, or NULL on failure.
    */
    const char* GetLocalIP() {
      char buf[256];
      if(gethostname(buf,sizeof(buf)))
        return NULL;
      struct hostent* he = gethostbyname(buf);
      if(!he)
        return NULL;
      for(int i=0; he->h_addr_list[i]; i++) {
        char* ip = inet_ntoa(*(struct in_addr*)he->h_addr_list[i]);
        if(ip != (char*)-1) return ip;
      }
      return NULL;
    }
    

    【讨论】:

    • 有时我的用户会为空,你知道是什么原因吗?
    • 很抱歉碰到了一个旧线程,但有人可以帮我把它转换成 swift 吗?
    【解决方案2】:

    你可以尝试使用类似这个服务: Whatismyip 并捕获字符串 :)

    感谢 Erica Sadun 的 iPhone Developer's Cookbok,第 2 版,第 555 页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      相关资源
      最近更新 更多