介绍两种收集来的本地DNS解析的方式
- (NSArray*)DNSBySystem:(NSString *)dominName{ Boolean result = '\0',bResolved; CFHostRef hostRef; CFArrayRef addresses = NULL; NSString *finalString = nil; char tempChar[1000]; NSMutableArray *ipResults = [NSMutableArray arrayWithCapacity:10]; strcpy(tempChar,(char *)[dominName UTF8String]); CFStringRef hostNameRef = CFStringCreateWithCString(kCFAllocatorDefault, tempChar, kCFStringEncodingASCII); hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostNameRef); if (hostRef) { result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); if (result == TRUE) { addresses = CFHostGetAddressing(hostRef, &result); } } bResolved = result == TRUE ? true : false; if(bResolved) { struct sockaddr_in* remoteAddr; for(int i = 0; i < CFArrayGetCount(addresses); i++) { CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addresses, i); remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData); if(remoteAddr != NULL) { //DNS解析结果cpy到char数组里 char ip[16]; strcpy(ip, inet_ntoa(remoteAddr->sin_addr)); finalString = [NSString stringWithCString:ip encoding:NSUTF8StringEncoding]; [ipResults addObject:finalString]; } } } CFRelease(hostNameRef); CFRelease(hostRef); return ipResults;}复制代码
上面这种方法在IPv6环境下解析有点问题,IPv4下无问题。下面这种方法两种环境下都适用
- (NSArray *)dnsByLocal:(NSString *)domain { if (domain.length == 0) { return nil; } struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_INET; hints.ai_protocol = IPPROTO_TCP; struct addrinfo *addrs, *addr; int getResult = getaddrinfo([domain UTF8String], NULL, &hints, &addrs); if (getResult || addrs == nil) { NSLog(@"Warn: DNS with domain:%@ failed:%d", domain, getResult); return nil; } addr = addrs; NSMutableArray *result = [NSMutableArray array]; for (addr = addrs; addr; addr = addr->ai_next) { char host[NI_MAXHOST]; memset(host, 0, NI_MAXHOST); getnameinfo(addr->ai_addr, addr->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST); if (strlen(host) != 0) { [result addObject:[NSString stringWithUTF8String:host]]; } } freeaddrinfo(addrs); NSLog(@"Info: DNS with domain:%@ -> %@", domain, result); return result;}复制代码