2011-07-14 125 views
0

我嘗試使用asyncsocket框架獲取IP地址。當通過以太網電纜進行時,以下方法效果很好。 但是當嘗試使用wifi接入點獲取IP地址時,它返回nil。獲取無線網絡地址問題

這裏有一個方法:

- (NSData *)wifiAddress 

{// 在iPhone上,無線網絡總是 「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; 

}

回答

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; 
} 
+0

我應該在(NSString *)接口參數中插入什麼? – Sergio

+0

我們只是使用「en」,所以任何帶有「en」的東西(例如en0,en1)都會被捕獲。 – tjg184