标签:
这里有两种方法:
1 //获取本机IP 2 - (NSString *)localIPAddress 3 { 4 NSString *localIP = nil; 5 struct ifaddrs *addrs; 6 if (getifaddrs(&addrs)==0) { 7 const struct ifaddrs *cursor = addrs; 8 while (cursor != NULL) { 9 if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0) 10 { 11 { 12 localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]; 13 break; 14 } 15 } 16 cursor = cursor->ifa_next; 17 } 18 freeifaddrs(addrs); 19 } 20 return localIP; 21 }
1 // 获取本机IP地址 2 - (NSString *)getIPAddress 3 { 4 NSString *address = @"error"; 5 struct ifaddrs *interfaces = NULL; 6 struct ifaddrs *temp_addr = NULL; 7 int success = 0; 8 9 // retrieve the current interfaces - returns 0 on success 10 success = getifaddrs(&interfaces); 11 if (success == 0) { 12 // Loop through linked list of interfaces 13 temp_addr = interfaces; 14 while (temp_addr != NULL) { 15 if( temp_addr->ifa_addr->sa_family == AF_INET) { 16 // Check if interface is en0 which is the wifi connection on the iPhone 17 if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { 18 // Get NSString from C String 19 address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; 20 } 21 } 22 23 temp_addr = temp_addr->ifa_next; 24 } 25 } 26 27 // Free memory 28 freeifaddrs(interfaces); 29 30 return address; 31 }
标签:
原文地址:http://www.cnblogs.com/zhizunbao/p/5575877.html