1

How do I get the IP from a given hostname on iOS?

I've tried Google but found nothing.

Hedam
  • 2,209
  • 27
  • 53
  • No, I want the IP of a hostname. Fx. I give the app the hostname Google.com and it returns the ip. – Hedam Aug 20 '13 at 20:45
  • Can't you just ping the hostname and capture the responding IP? – Luke Aug 20 '13 at 20:47
  • Ok then [this one](http://stackoverflow.com/questions/9567521/obtaining-a-server-ip-address-from-hostname) –  Aug 20 '13 at 20:47
  • http://stackoverflow.com/questions/5450621/how-to-get-the-external-ip-in-objective-c is about determining the "external" IP address of a device behind a firewall, so this is **not a duplicate** of that question. – Martin R Aug 20 '13 at 21:08
  • @user2062950, while that does give a reasonable answer, MartinR's answer below is preferable. getnameinfo() has replace gethostbyname(). – Rob Napier Aug 20 '13 at 21:42

1 Answers1

9

The following code works with both IPv4 and IPv6. It uses getaddrinfo() to retrieve a list of IP addresses for a host, and getnameinfo() to convert each IP address into a string. (Error checking omitted for brevity.)

struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;        // PF_INET if you want only IPv4 addresses
hints.ai_protocol = IPPROTO_TCP;

struct addrinfo *addrs, *addr;

getaddrinfo("www.google.com", NULL, &hints, &addrs);
for (addr = addrs; addr; addr = addr->ai_next) {

    char host[NI_MAXHOST];
    getnameinfo(addr->ai_addr, addr->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    printf("%s\n", host);

}
freeaddrinfo(addrs);
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Got this error: Definition of 'struct addrinfo' must be imported from module 'Darwin.POSIX.netdb' before it is required – Hedam Aug 21 '13 at 16:12
  • 5
    @RoboForm: You have to add some include files. If you type "man getaddrinfo" on the command line you will see what include files are needed. – Martin R Aug 21 '13 at 16:14