Friday, March 25, 2011

Resolve the IP Number from a Host Name

This sample translate the IP number from www.google.com. But you can even use localhost or localmachinename to gets the local or external IP number of the local machine.

#include <stdio.h>
#include <iostream>
#include <arpa/inet.h>
#include <netdb.h>
int main() {
  char hostName[] = "www.google.com";
  struct hostent *host;
  if ((host = gethostbyname(hostName)) == NULL) {
    fprintf(stderr, "(mini) nslookup failed on '%s'", hostName);
    return 1;
  }
  struct in_addr h_addr;
  h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
  const char *ip = inet_ntoa(h_addr);
  std::cout << ip << std::endl;
  return 0;
}

No comments:

Post a Comment