Last active
May 9, 2016 10:57
-
-
Save msching/e0cd6e0e76d70ec78e6d538ab9e6c87c to your computer and use it in GitHub Desktop.
addressesForHostname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (NSArray *)addressesForHostname:(NSString *)hostname | |
{ | |
if (!hostname) | |
{ | |
return nil; | |
} | |
// Get the addresses for the given hostname. | |
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)hostname); | |
BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil); | |
if (!isSuccess) | |
{ | |
CFRelease(hostRef); | |
return nil; | |
} | |
CFArrayRef addressesRef = CFHostGetAddressing(hostRef, nil); | |
if (!addressesRef) | |
{ | |
CFRelease(hostRef); | |
return nil; | |
} | |
CFRelease(hostRef); | |
// Convert these addresses into strings. | |
char ipAddress[INET6_ADDRSTRLEN]; | |
NSMutableArray *addresses = [NSMutableArray array]; | |
CFIndex numAddresses = CFArrayGetCount(addressesRef); | |
for (CFIndex currentIndex = 0; currentIndex < numAddresses; currentIndex++) | |
{ | |
struct sockaddr *address = (struct sockaddr *)CFDataGetBytePtr(CFArrayGetValueAtIndex(addressesRef, currentIndex)); | |
if (!address) | |
{ | |
return nil; | |
} | |
getnameinfo(address, address->sa_len, ipAddress, INET6_ADDRSTRLEN, nil, 0, NI_NUMERICHOST); | |
if (!ipAddress) | |
{ | |
return nil; | |
} | |
[addresses addObject:[NSString stringWithCString:ipAddress encoding:NSASCIIStringEncoding]]; | |
} | |
return addresses; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment