Tag Archive - c

gethostbyname in C

As a comparison to my earlier post. Doing this in C is much more efficient. This code prints out 2 (of the 3) A records for test.poller.se.

#include <stdio.h>
#include <netdb.h>
 
struct hostent *he;
struct in_addr **hosts;
 
main(void) {
        he = gethostbyname("test.poller.se");
 
        hosts = (struct in_addr **)he-&gt;h_addr_list;
 
        printf("%s\n", inet_ntoa(*hosts[0]));
        printf("%s\n", inet_ntoa(*hosts[1]));
 
        return 0;
}

This is much faster then the perl approach.

$ time for i in `seq 1 1000`; do ./gethostbyname > /dev/null; done
real    0m10.393s
user    0m0.764s
sys     0m9.065s