Our requirement is to resolve a host address with CDN through the domain name of the host, get 10 IP addresses and make sorting and optimal strategy respectively for data communication. However, we tried many methods, but could not directly obtain enough IP addresses, so we suspected that the underlying interface had made a preferential policy when returning.
At the same time, of course, android colleagues were given random DNS IP addresses.
Well, without further ado, go directly to the code, a lot of code on the Internet is C method, I do not like to use this kind of high-end, but not flexible way
- (NSArray *)queryDNSforHost:(NSString *)hostname {CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)hostname); Boolean result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); if (result == TRUE) { NSArray *addresses = (__bridge NSArray*)CFHostGetAddressing(hostRef, &result); NSMutableArray *tempDNS = [[NSMutableArray alloc] init]; for(int i = 0; i < addresses.count; i++){ struct sockaddr_in* remoteAddr; CFDataRef saData = (__bridge CFDataRef)addresses[i]; remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData); if(remoteAddr ! = NULL){ NSString *strDNS =[NSString stringWithCString:inet_ntoa(remoteAddr->sin_addr) encoding:NSASCIIStringEncoding]; If ([strDNS isEqualToString:@"0.0.0.0"]) {continue; } [tempDNS addObject:strDNS]; } } return tempDNS; }else{ return nil; }}Copy the code
Don’t forget #include < ARPA /inet.h>