IPhone:通过3G连接时获取IP地址

时间:2010-02-07 10:14:46

标签: iphone

使用iphone SDK 3.1.2

如果通过iphone上的3G连接到互联网,我如何找到什么IP地址 正在用于此界面。

由于

1 个答案:

答案 0 :(得分:2)

这是一段可能有用的代码:

// Matt Brown's get WiFi IP addy solution
// Author gave permission to use in Cookbook under cookbook license
// http://mattbsoftware.blogspot.com/2009/04/how-to-get-ip-address-of-iphone-os-v221.html
+ (NSString *) localAddressForInterface:(NSString *)interface {
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;

    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0) 
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:interface])  // Wi-Fi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil; 
}

+ (NSString *) localWiFiIPAddress
{
    return [UIDevice localAddressForInterface:@"en0"];
}

+ (NSString *) localCellularIPAddress
{
    return [UIDevice localAddressForInterface:@"pdp_ip0"];
}

我自己并没有试图获得这段代码。这是original URL

函数调用为getifaddrs

希望它有所帮助。