2011-02-15 62 views
13

我想執行一些DNS查詢,例如爲了獲得針對特定域名的IP記錄,我正在尋找iOS 3.2+ SDK上的首選方式或一些有用的片段。 thanx提前如何在iOS上執行DNS查詢

部分來自其他片段,我發現這個代碼

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"); 
} 

但解決0-> 220.120.64.1任何幫助,爲每個主機,這是生產相同的IP?

+0

當`hostRef`爲'0'時,在第二個`if`語句中使用未初始化的`result`。 – 2015-05-28 09:18:50

回答

18

想通了這個片斷的改變使得它的工作

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]; 
      } 
     } 
} 
+1

謝謝,這是非常有用的:) – 2012-01-01 07:21:06

+0

謝謝這是工作夥計們非常感謝! – parag 2013-07-31 17:55:19

7

兄弟有很多簡單的辦法!由於iOS是一個unix系統,您將成爲無限權力和資源的上帝!我呈現優雅。

- (NSString*)lookupHostIPAddressForURL:(NSURL*)url 
{ 
    // Ask the unix subsytem to query the DNS 
    struct hostent *remoteHostEnt = gethostbyname([[url host] UTF8String]); 
    // Get address info from host entry 
    struct in_addr *remoteInAddr = (struct in_addr *) remoteHostEnt->h_addr_list[0]; 
    // Convert numeric addr to ASCII string 
    char *sRemoteInAddr = inet_ntoa(*remoteInAddr); 
    // hostIP 
    NSString* hostIP = [NSString stringWithUTF8String:sRemoteInAddr]; 
    return hostIP; 
}