Created
October 11, 2012 17:03
-
-
Save mcgaffin/3873928 to your computer and use it in GitHub Desktop.
iOS: how to get the ip address of a remote 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
// adapted from: http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone | |
- (NSString *)getIPAddress { | |
Boolean result; | |
CFHostRef hostRef; | |
CFArrayRef addresses; | |
NSString *hostname = @"domain.myhost.com"; | |
NSString *ipAddress = @""; | |
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) { | |
CFIndex index = 0; | |
CFDataRef ref = (CFDataRef) CFArrayGetValueAtIndex(addresses, index); | |
struct sockaddr_in* remoteAddr; | |
char *ip_address; | |
remoteAddr = (struct sockaddr_in*) CFDataGetBytePtr(ref); | |
if (remoteAddr != NULL) { | |
ip_address = inet_ntoa(remoteAddr->sin_addr); | |
} | |
ipAddress = [NSString stringWithCString:ip_address encoding:NSUTF8StringEncoding]; | |
} | |
return ipAddress; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment