user2817653
user2817653

Reputation: 35

Resolve string of hostname to string of IP

I am making an iPhone app and I need to resolve a string of a hostname into a string of an IP address. For example, "MyComputer.local" -> "192.168.0.7". I have tried doing a few things, but none have worked. This is what I have right now:

struct hostent *hostentry;
hostentry = gethostbyname("MyComputer.local");
char *ipbuf = NULL;
inet_ntop(AF_INET, hostentry->h_addr_list[0], ipbuf, hostentry->h_length);
ipAddress = [NSString stringWithFormat:@"%s" , ipbuf];

For some reason, it always crashes on the inet_ntop, and yes, I am using an existing hostname to test. Thanks!

Upvotes: 3

Views: 648

Answers (1)

zaph
zaph

Reputation: 112875

In place of inet_ntop try inet_ntoa.

It helps to break compound statements up a little:

struct hostent *hostentry;
hostentry = gethostbyname("zaph.com");
NSLog(@"name: %s", hostentry->h_name);

struct in_addr **addr_list;
addr_list = (struct in_addr **)hostentry->h_addr_list;
char* ipAddr = inet_ntoa(*addr_list[0]);

NSString *ipAddress = [NSString stringWithFormat:@"%s", ipAddr];
NSLog(@"ipAddress: %@", ipAddress);

Output:

name: zaph.com
ipAddress: 72.35.89.108

Upvotes: 2

Related Questions