iOS 获取IP地址方法
闲来无事做个东西要获取iPhone的ip地址,网上好多方法没法用,这有一个能用的,记录下来。
代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| 引入文件
获取ip地址 -(void)getIPaddress { NSString *address = @"error"; struct ifaddrs * ifaddress = NULL; struct ifaddrs * temp_address = NULL; int success = 0; success = getifaddrs(&ifaddress); if(success == 0) { temp_address = ifaddress; while(temp_address != NULL) { if(temp_address->ifa_addr->sa_family == AF_INET) { if([[NSString stringWithUTF8String:temp_address->ifa_name] isEqualToString:@"en0"]) { address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_address->ifa_addr)->sin_addr)]; } } temp_address = temp_address->ifa_next; } }
NSLog(@"获取到的IP地址为:%@",address); }
|