Created
April 21, 2012 05:58
-
-
Save xhan/2434542 to your computer and use it in GitHub Desktop.
get ip address of specific Host
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
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
Boolean result; | |
CFHostRef hostRef; | |
CFArrayRef addresses; | |
NSString *hostname = @"m2.qiushibaike.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 = CFHostGetAddressing(hostRef, &result); | |
} | |
} | |
if (result == TRUE) { | |
// NSLog(@"Resolved"); | |
// CFStringRef description = CFCopyDescription(addresses); | |
// NSLog(@"Array %@", description); | |
// Iterate through the records to extract the address information | |
struct sockaddr_in* remoteAddr; | |
for(int i = 0; i < CFArrayGetCount(addresses); i++) | |
{ | |
CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addresses, i); | |
remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData); | |
if(remoteAddr != NULL) | |
{ | |
// Extract the ip address | |
// inet_ntoa(remoteAddr->sin_addr); | |
char *ip = inet_ntoa(remoteAddr->sin_addr); | |
NSLog(@"!!!!!!!! %s",ip); | |
} | |
} | |
} else { | |
NSLog(@"Not resolved"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment