一次在做获取硬件信息的时候,需要获取所连接网络的IP地址,
首先导入头文件:
#import <ifaddrs.h>
#import <arpa/inet.h>
方法:
+ (NSString*)getCurentLocalIP{
NSString*address =nil;
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) {
NSLog(@"%d",temp_addr->ifa_addr->sa_family);
if(temp_addr->ifa_addr->sa_family==AF_INET|| temp_addr->ifa_addr->sa_family==AF_INET6|| temp_addr->ifa_addr->sa_family==AF_LINK) {
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);
return address;
}
此方法可以直接调用,如果是tvOS,将en0改为en1,这是固定的写法。