Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何以编程方式获取iphone的ip地址_Iphone_Objective C_Ipad_Ip Address - Fatal编程技术网

如何以编程方式获取iphone的ip地址

如何以编程方式获取iphone的ip地址,iphone,objective-c,ipad,ip-address,Iphone,Objective C,Ipad,Ip Address,我用iphone安装并运行了一个Web服务器。但问题是,我如何获得iphone/ipad的ip地址,让用户知道他们可以在哪里访问服务器。我发现[NSHost addresses]可以完成这项工作,但我正在为app store开发,这是一种没有文档记录的方法。\include #include <ifaddrs.h> #include <arpa/inet.h> // Get the INTERNAL ip address - (NSString *)getIPAddr

我用iphone安装并运行了一个Web服务器。但问题是,我如何获得iphone/ipad的ip地址,让用户知道他们可以在哪里访问服务器。我发现
[NSHost addresses]
可以完成这项工作,但我正在为app store开发,这是一种没有文档记录的方法。

\include
#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;

} 

#包括

我相信
[NSHost address]已记录,如下所示:


使用
[[NSHost currentHost]地址]获取IP。

它可用于Mac OS。。。不适用于iOS!!避免使用NSHost:它不是线程安全的。它必须在主线程上运行,它是阻塞的,不确定的。由于它,我出现了一个明显但难以解释的僵局:(这在iOS 8上可用。@AbhiBeckert,我错过了什么?我似乎无法在iOS上使用它8@JohnRiselvato我不知道发生了什么。8月份我在iOS 8上使用了NSHost,但最终我从我的应用程序中删除了该功能。在
文件->快速打开中键入NSHost会打开NSStream.h,但该文件无法继续ain是这个类的定义。很奇怪。也许苹果不小心将它从一个私有API切换到了一个公共API,然后又将其反转了?苹果正式接受了吗?这提供了一个不同的ip地址,这个ip地址也适用于IPv6@Mathieu,还有一些人问为什么这个方法提供的地址与您从whatsmyip.org获得的地址不同等等-这是因为此方法提供了您的本地IP地址。也就是说,您的局域网(家庭集线器、WiFi网络、办公室内部网等)上的其他设备所使用的IP地址将用于与您的设备通话。这些地址通常以10.或192.168.开头,这将它们标记为内部的、不可从internet地址路由的地址。WhatsMyIP.org提供您的外部IP地址,这是您的本地网络网关地址,并且您局域网上的所有设备都共享该地址。始终返回错误:(如果另一个问题没有标记答案,这怎么会是重复的?@Morkrom标记答案只与一个人相关:最初写问题的人。