2013-03-28 43 views
3

我喜歡在我的應用程序中顯示IP地址,我已經知道如何顯示WiFi IP地址,但是當我在蜂窩電話時它將顯示錯誤,那麼是否有方法顯示iPhone上的蜂窩IP地址?如何在iOS應用程序中獲取蜂窩IP地址

這裏是我使用的無線IP地址代碼:

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

    NSLog(address); 
+0

什麼錯誤信息,你得到什麼?蜂窩網絡的接口名稱可能不是「en0」?您的代碼僅適用於IPv4地址。有關枚舉所有本地IPv4和IPv6接口地址的代碼,請參閱(例如)http://stackoverflow.com/a/14084031/1187415,這可能會有所幫助。 –

+0

@Martin R我沒有得到任何錯誤,IP地址的字符串只是(錯誤) –

+0

蜂窩網絡的接口可能有不同的名稱(不是「en0」)。嘗試枚舉* all *接口,也許您可​​以識別蜂窩網絡的接口。也嘗試IPv6(請參閱我以前的評論中的鏈接)。 –

回答

14

我finaly做到了,我用這個代碼:

struct ifaddrs *interfaces = NULL; 
    struct ifaddrs *temp_addr = NULL; 
    NSString *wifiAddress = nil; 
    NSString *cellAddress = nil; 

    // retrieve the current interfaces - returns 0 on success 
    if(!getifaddrs(&interfaces)) { 
     // Loop through linked list of interfaces 
     temp_addr = interfaces; 
     while(temp_addr != NULL) { 
      sa_family_t sa_type = temp_addr->ifa_addr->sa_family; 
      if(sa_type == AF_INET || sa_type == AF_INET6) { 
       NSString *name = [NSString stringWithUTF8String:temp_addr->ifa_name]; 
       NSString *addr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; // pdp_ip0 
       //NSLog(@"NAME: \"%@\" addr: %@", name, addr); // see for yourself 

       if([name isEqualToString:@"en0"]) { 
        // Interface is the wifi connection on the iPhone 
        wifiAddress = addr; 
       } else 
        if([name isEqualToString:@"pdp_ip0"]) { 
         // Interface is the cell connection on the iPhone 
         cellAddress = addr; 
        } 
      } 
      temp_addr = temp_addr->ifa_next; 
     } 
     // Free memory 
     freeifaddrs(interfaces); 
    } 
    NSString *addr = wifiAddress ? wifiAddress : cellAddress; 

    NSLog(addr); 
+2

請注意'inet_ntoa'只適用於IPv4地址。如果您在IPv6網絡中,則必須使用'inet_ntop'或更好''getnameinfo'。 –

+2

Wi-Fi IP不是外部IP。 – Mahouk

+0

你也應該檢查哪個網絡實際連接,在我的代碼中,wifiAddress = addr;被執行了兩次 –