Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

iphone - How to perform DNS query on iOS

i want to perform some DNS queries e.g. to get IP records against a specific domain name, i am looking for a preferred way or some useful snippet for this on iOS 3.2+ SDK. thanx in advance

part from other snippets i found this code

 Boolean result;
 CFHostRef hostRef;
 NSArray *addresses;
 NSString *hostname = @"apple.com";
 hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
 if (hostRef) {
      result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
      if (result == TRUE) {
           addresses = (NSArray*)CFHostGetAddressing(hostRef, &result);
      }
 }
 if (result == TRUE) {
      [addresses enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
             NSString *strDNS = [NSString stringWithUTF8String:inet_ntoa(*((struct in_addr *)obj))];
           NSLog(@"Resolved %d->%@", idx, strDNS);
      }];

 } else {
      NSLog(@"Not resolved");
 }

but this is producing same IP for every host Resolved 0->220.120.64.1 any help??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Figured out a change in this snippet makes it working

if (result == TRUE) {
        NSMutableArray *tempDNS = [[NSMutableArray alloc] init];
        for(int i = 0; i < CFArrayGetCount(addresses); i++){
            struct sockaddr_in* remoteAddr;
            CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addresses, i);
            remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData);

            if(remoteAddr != NULL){
                // Extract the ip address
                //const char *strIP41 = inet_ntoa(remoteAddr->sin_addr);
                NSString *strDNS =[NSString stringWithCString:inet_ntoa(remoteAddr->sin_addr) encoding:NSASCIIStringEncoding];
                NSLog(@"RESOLVED %d:<%@>", i, strDNS);
                [tempDNS addObject:strDNS];
            }
        }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...