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

use*_*812 36 iphone objective-c ip-address ipad

我使用Mongoose在iphone中启动并运行了一个Web服务器.但问题是如何让我的iphone/ipad的IP地址让用户知道他们可以访问服务器的位置.我发现[NSHost addresses]可以完成这项工作,但我正在开发app app,这是一种无证的方法.

Sau*_*abh 116

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

} 
Run Code Online (Sandbox Code Playgroud)

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

  • 这提供了与http://www.whatsmyip.org/不同的IP地址 (7认同)
  • @Mathieu和其他人问为什么这个方法给出的地址与你从whatsmyip.org等获得的地址不同 - 这是因为这个方法给出了你的LOCAL IP地址.也就是说,您的局域网(家庭集线器,WiFi网络,办公室内部网等)上的其他设备将用于与您的设备通信的IP.这些地址通常以10.或192.168开头.这标志着它们是来自互联网地址的内部,不可路由的.WhatsMyIP.org提供您的外部IP地址,这是您的本地网络网关地址,并且您所在地区网络上的所有设备都共享它. (4认同)
  • 总是返回错误:( (2认同)