simple gethostbyname example
Here’s a simple example using gethostbyname() that emulates the host command. I wrote it to debug a DNS problem. (On the network I’m on right now, gethostbyname() returns a different answer than host and dig. It is overagressively caching other hostnames. i.e. paulloookup shrub.ca is returning 17.250.248.64, which is mail.mac.com (!)
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc < 2) {
printf(“Usage: %s hostname”, argv[0]);
exit(-1);
}
struct hostent *hp = gethostbyname(argv[1]);
if (hp == NULL) {
printf(“gethostbyname() failed\n”);
} else {
printf(“%s = “, hp->h_name);
unsigned int i=0;
while ( hp -> h_addr_list[i] != NULL) {
printf( “%s “, inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[i])));
i++;
}
printf(“\n”);
}
}