导入头文件
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
1 #pragma mark - 获取本机地址 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 //NSString *name = [NSString stringWithUTF8String:cursor->ifa_name]; 12 //if ([name isEqualToString:@"en0"]) // Wi-Fi adapter 13 { 14 localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]; 15 break; 16 } 17 } 18 cursor = cursor->ifa_next; 19 } 20 freeifaddrs(addrs); 21 } 22 return localIP; 23 }