获取域名对应的IP
#import <netdb.h>
- (NSArray *)ipWithHose:(NSString *)host{
const char *szname = [host UTF8String];
struct hostent *phot = gethostbyname(szname);
struct in_addr ip_addr;
// - 192.192.192.192 长度
int ipSize = 15;
int addrSize = sizeof(ip_addr);
char *ipPtr = malloc(ipSize);
// - 保存查询到的ip地址
NSMutableArray *ips = [NSMutableArray array];
for(char **pptr = phot->h_addr_list; *pptr != NULL; pptr++){
memcpy(&ip_addr, *pptr ,addrSize);
memset(ipPtr, 0, ipSize);
inet_ntop(AF_INET, &ip_addr, ipPtr, ipSize);
NSString *ipStr = [NSString stringWithUTF8String:ipPtr];
[ips addObject:ipStr];
}
// - 释放内存
free(ipPtr);
return ips;
}
获取局域网的IP地址
+ (NSString *)IPAddress{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET && [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}
获取DNS地址
+ (void)DNSAddress{
res_state res = malloc(sizeof(struct __res_state));
int result = res_ninit(res);
if (!result){
res_nclose(res);
return;
}
for ( int i = 0; i < res->nscount; i++ ){
NSString *s = [NSString stringWithUTF8String : inet_ntoa(res->nsaddr_list[i].sin_addr)];
NSLog(@"// - 李超群 console [error] ...xx");
}
res_nclose(res);
}