|
11 | 11 |
|
12 | 12 | #import "QNDns.h" |
13 | 13 |
|
| 14 | +static NSArray *getAddresses(CFHostRef hostRef) { |
| 15 | + Boolean lookup = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); |
| 16 | + if (!lookup) { |
| 17 | + return nil; |
| 18 | + } |
| 19 | + CFArrayRef addresses = CFHostGetAddressing(hostRef, &lookup); |
| 20 | + if (!lookup) { |
| 21 | + return nil; |
| 22 | + } |
| 23 | + |
| 24 | + char buf[32]; |
| 25 | + __block NSMutableArray *ret = [[NSMutableArray alloc] init]; |
| 26 | + |
| 27 | + // Iterate through the records to extract the address information |
| 28 | + struct sockaddr_in *remoteAddr; |
| 29 | + for (int i = 0; i < CFArrayGetCount(addresses); i++) { |
| 30 | + CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addresses, i); |
| 31 | + remoteAddr = (struct sockaddr_in *)CFDataGetBytePtr(saData); |
| 32 | + |
| 33 | + if (remoteAddr != NULL) { |
| 34 | + const char *p = inet_ntop(AF_INET, &(remoteAddr->sin_addr), buf, 32); |
| 35 | + NSString *ip = [NSString stringWithUTF8String:p]; |
| 36 | + [ret addObject:ip]; |
| 37 | + NSLog(@"Resolved %u->%@", i, ip); |
| 38 | + } |
| 39 | + } |
| 40 | + return ret; |
| 41 | +} |
| 42 | + |
14 | 43 | @implementation QNDns |
15 | 44 |
|
16 | 45 | + (NSArray *)getAddresses:(NSString *)hostName { |
17 | | - CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)hostName); |
| 46 | + // Convert the hostname into a StringRef |
| 47 | + CFStringRef hostNameRef = CFStringCreateWithCString(kCFAllocatorDefault, [hostName UTF8String], kCFStringEncodingASCII); |
18 | 48 |
|
19 | | - Boolean lookup = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); |
20 | | - NSArray *addresses = (__bridge NSArray *)CFHostGetAddressing(hostRef, &lookup); |
21 | | - __block NSMutableArray *ret = [[NSMutableArray alloc] init]; |
22 | | - [addresses enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { |
23 | | - struct in_addr *data = (__bridge struct in_addr *)obj; |
24 | | - char buf[32]; |
25 | | - const char *p = inet_ntop(AF_INET, (void *)data, buf, 32); |
26 | | - NSString *ip = [NSString stringWithUTF8String:p]; |
27 | | - [ret addObject:ip]; |
28 | | -// NSLog(@"Resolved %lu->%@", (unsigned long)idx, ip); |
29 | | - }]; |
| 49 | + CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostNameRef); |
| 50 | + NSArray *ret = getAddresses(hostRef); |
| 51 | + |
| 52 | + CFRelease(hostRef); |
| 53 | + CFRelease(hostNameRef); |
30 | 54 | return ret; |
31 | 55 | } |
32 | 56 |
|
33 | 57 | + (NSString *)getAddressesString:(NSString *)hostName { |
34 | 58 | NSArray *result = [QNDns getAddresses:hostName]; |
35 | | - if (result.count == 0) { |
| 59 | + if (result == nil || result.count == 0) { |
36 | 60 | return @""; |
37 | 61 | } |
38 | 62 | return [result componentsJoinedByString:@";"]; |
|
0 commit comments