Skip to content

Instantly share code, notes, and snippets.

@msching
Last active May 9, 2016 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msching/e0cd6e0e76d70ec78e6d538ab9e6c87c to your computer and use it in GitHub Desktop.
Save msching/e0cd6e0e76d70ec78e6d538ab9e6c87c to your computer and use it in GitHub Desktop.
addressesForHostname
+ (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