Skip to content

Instantly share code, notes, and snippets.

@p120ph37
Created November 21, 2020 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p120ph37/e06bd88abad0a7aceb2b9d2d5552529c to your computer and use it in GitHub Desktop.
Save p120ph37/e06bd88abad0a7aceb2b9d2d5552529c to your computer and use it in GitHub Desktop.
Monitor the latency of hostname resolution
#include <arpa/inet.h>
#include <limits.h>
#include <math.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
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;
}
@p120ph37
Copy link
Author

Example usage:

~ $ gcc dnsping.c -o dnsping
~ $ ./dnsping -c 3 -i 1 example.com
example.com -> example.com(93.184.216.34) 36.003ms
example.com -> example.com(93.184.216.34) 0.857ms
example.com -> example.com(93.184.216.34) 0.935ms
~ $

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment