如何以编程方式获取iPhone的IP地址

38

我使用Mongoose在 iPhone 上搭建网页服务器,但问题是如何获取我的 iPhone/iPad 的 IP 地址,以让用户知道他们可以在哪里访问该服务器。我发现[NSHost addresses]能够完成此任务,但我正在为 App Store 进行开发,而这是未经记录的方法。


如果另一个问题没有标记的答案,那么这怎么算是重复问题呢? - Morkrom
@Morkrom 标记的答案只与一个人有关:最初提出问题的那个人。 - Cœur
2个回答

123
#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;

} 

如何查找iPhone的IP地址?


1
它是否被苹果官方认可? - Raptor
8
这会给出一个不同于http://www.whatsmyip.org/的IP地址。 - Yunus Nedim Mehel
1
这个可以同时适用于IPv6 https://stackoverflow.com/questions/33125710/how-to-get-ipv6-interface-address-using-getifaddr-function/33127330#33127330 - lucianoenrico
4
这种方法得到的地址与 whatsmyip.org 等网站得到的地址不同,Mathieu 和其他人想知道原因。这是因为这种方法提供的是你的本地 IP 地址,也就是其他设备在你所连接的局域网中(如家庭网络、Wi-Fi 网络、公司内网等)使用来与你的设备通信的地址。这些地址通常以10.或192.168.开头,标识它们是内部地址,在互联网上无法路由。而 WhatsMyIP.org 提供的是你的外部 IP 地址,也就是你的本地网络网关地址,所有连接到该局域网的设备共享此地址。 - Simon Tillson
2
总是返回错误 :( - user3236289
显示剩余12条评论

-1

13
仅适用于Mac OS,不支持iOS! - user757812
4
避免使用NSHost:它不是线程安全的。它必须在主线程上运行,它会阻塞并且不确定性高。由于它而产生了一个明显但难以解释的死锁 :( - Matt Melton
3
可在iOS 8上使用。 - Abhi Beckert
3
@AbhiBeckert,我有所遗漏吗?我似乎无法在iOS 8上使这个工作。 - John Riselvato
3
我不确定发生了什么事情。我在8月份在iOS 8上使用NSHost,但最终将该功能从我的应用程序中删除了。在“文件->快速打开”中输入NSHost会弹出NSStream.h,但是该文件没有包含该类的定义。很奇怪。也许苹果公司意外地将其从私有API切换为公共API,然后又逆转了呢? - Abhi Beckert
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接