我喜歡在我的應用程序中顯示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);
什麼錯誤信息,你得到什麼?蜂窩網絡的接口名稱可能不是「en0」?您的代碼僅適用於IPv4地址。有關枚舉所有本地IPv4和IPv6接口地址的代碼,請參閱(例如)http://stackoverflow.com/a/14084031/1187415,這可能會有所幫助。 –
@Martin R我沒有得到任何錯誤,IP地址的字符串只是(錯誤) –
蜂窩網絡的接口可能有不同的名稱(不是「en0」)。嘗試枚舉* all *接口,也許您可以識別蜂窩網絡的接口。也嘗試IPv6(請參閱我以前的評論中的鏈接)。 –