#include #include #include #include #include #include #include #include extern int h_errno; void usage(const char *argv0) { fprintf(stderr, "Usage: %s [-c count] [-i secs] example.com\n", argv0); } void dsleep(double duration) { if(duration > 0) { double i, f = modf(duration, &i); struct timespec ts = { i, 1000000000.0 * f }; while(nanosleep(&ts, &ts)) { } } } int main(int argc, char **argv) { int c; long count = 0; double interval = 1; char *domain = NULL; while(getopt(argc, argv, "c:i:") != -1) { switch(optopt) { case 'c': count = atoi(optarg); break; case 'i': interval = atof(optarg); break; default: usage(argv[0]); return 1; } } if(optind >= argc) { fprintf(stderr, "Expected a domain name to resolve.\n"); usage(argv[0]); return 1; } domain = argv[optind]; if(count == 0) count = LONG_MAX; struct hostent *host = NULL; double elapsed = interval; for(long i = 0; i < count; i++) { dsleep(interval - elapsed); printf("%s -> ", domain); struct timeval t1, t2; gettimeofday(&t1, NULL); host = gethostbyname(domain); gettimeofday(&t2, NULL); if(host == NULL) { switch(h_errno) { case HOST_NOT_FOUND: printf("[HOST_NOT_FOUND]"); break; case NO_DATA: printf("[NO_DATA]"); break; case NO_RECOVERY: printf("[NO_RECOVERY]"); break; case TRY_AGAIN: printf("[TRY_AGAIN]"); break; default: printf("[%d]", h_errno); } } else { struct in_addr *addr = (struct in_addr*)(host->h_addr_list[0]); printf("%s(%s)", host->h_name, inet_ntoa(*addr)); } elapsed = (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1000000.0; printf(" %#.3fms\n", elapsed * 1000.0); } return host == NULL ? -1 : h_errno; }