使用iphone SDK 3.1.2
如果通过iphone上的3G连接到互联网,我如何找到什么IP地址 正在用于此界面。
由于
答案 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。
希望它有所帮助。