我尝试使用asyncsocket框架获取ip地址。什么时候通过以太网电缆,以下方法工作正常。 但是当尝试使用wifi接入点获取IP地址时,它返回nil。
这是一种方法:
- (NSData *)wifiAddress
{ //在iPhone上,WiFi总是“en0”
NSData *result = nil;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
NSLog(@"cursor->ifa_name = %s", cursor->ifa_name);
if (strcmp(cursor->ifa_name, "en0") == 0)
{
if (cursor->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *)cursor->ifa_addr;
NSLog(@"cursor->ifa_addr = %s", inet_ntoa(addr->sin_addr));
result = [NSData dataWithBytes:addr length:sizeof(struct sockaddr_in)];
cursor = NULL;
}
else
{
cursor = cursor->ifa_next;
}
}
else
{
cursor = cursor->ifa_next;
}
}
freeifaddrs(addrs);
}
return result;
}
答案 0 :(得分:1)
我们遇到的问题是en0上的完全匹配并不总是返回wifi地址。我们有类似于以下内容。希望这可以帮助。
NSString* wifiIp = [NetUtils getLocalAddress:@"en"];
+ (NSString *) getLocalAddress:(NSString*) interface
{
NSString *address = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0)
{
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
NSRange range = [[NSString stringWithUTF8String:temp_addr->ifa_name] rangeOfString : interface];
if(range.location != NSNotFound)
{
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}