【问题标题】:how to get ip address of iphone programmatically [duplicate]如何以编程方式获取iphone的IP地址[重复]
【发布时间】:2011-10-12 01:48:47
【问题描述】:

我使用Mongoose 在 iphone 中启动并运行了一个网络服务器。但问题是如何获取我的 iphone/ipad 的 IP 地址,让用户知道他们可以在哪里访问服务器。我发现[NSHost addresses] 可以完成这项工作,但我正在为应用商店开发,这是未记录的方法。

【问题讨论】:

  • 如果另一个问题没有标记答案,这怎么会是重复的?
  • @Morkrom 一个标记的答案只与一个人相关:最初写这个问题的人。

标签: iphone objective-c ipad ip-address


【解决方案1】:
#include <ifaddrs.h>
#include <arpa/inet.h>

// Get the INTERNAL ip address

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

} 

https://web.archive.org/web/20160527165909/http://www.makebetterthings.com/iphone/how-to-find-ip-address-of-iphone/

【讨论】:

  • 苹果官方接受了吗?
  • 这给出了一个不同于whatsmyip.org的IP地址
  • @Mathieu 和其他人询问为什么此方法提供的地址与您从 whatsmyip.org 等获得的地址不同 - 那是因为此方法提供了您的本地 IP 地址。也就是说,您局域网上的其他设备(家庭集线器、WiFi 网络、办公室内部网等)将用来与您的设备通信的 IP。这些地址通常以 10. 或 192.168 开头。这将它们标记为内部的,无法从 Internet 地址路由。 WhatsMyIP.org 提供您的外部 IP 地址,这是您的本地网络网关地址,您的局域网上的所有设备都共享它。
  • 总是返回错误:(
【解决方案2】:

我相信[NSHost address]; 已记录在案,它在此处列出: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSHost_Class/Reference/Reference.html

使用[[NSHost currentHost] address];获取IP。

【讨论】:

  • 它适用于 Mac OS ...不适用于 iOS!
  • 避免使用 NSHost:它不是线程安全的。它必须在主线程上运行,它是阻塞的并且不是确定性的。由于它,我遇到了一个明显但难以解释的僵局:(
  • 这在 iOS 8 上可用。
  • @AbhiBeckert,我错过了什么吗?我似乎无法在 iOS 8 上使用它
  • @JohnRiselvato 我不确定发生了什么。我在 8 月份在 iOS 8 上使用 NSHost,但最终我从我的应用程序中删除了该功能。将 NSHost 键入file -&gt; open quickly 会显示 NSStream.h 但该文件不包含该类的定义。诡异的。也许 Apple 不小心将其从私有 API 转换为公共 API,然后又将其反转?
猜你喜欢
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2016-07-12
  • 2023-03-27
  • 2013-12-30
  • 1970-01-01
相关资源
最近更新 更多