C gethostbyname example
September 25, 2011 21:41:15 Last update: September 25, 2011 21:41:30
A simple C example for IP address lookup with
gethostbyname.
#include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s hostname\n", argv[0]); exit(1); } struct hostent *host = gethostbyname(argv[1]); if (host == NULL) { perror("host lookup"); exit(1); } int i=0; printf("%s IPs: ", host->h_name); while (host->h_addr_list[i] != NULL) { printf("%s ", inet_ntoa(*(struct in_addr*)(host->h_addr_list[i]))); i++; } printf("\n"); }