Skip to content

Instantly share code, notes, and snippets.

@nchaimov
Created March 14, 2017 22:41
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 nchaimov/4e4c4277e3b2b26096778c1d88c8a663 to your computer and use it in GitHub Desktop.
Save nchaimov/4e4c4277e3b2b26096778c1d88c8a663 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int lookup_host (const char *host, int use_canonname) {
struct addrinfo hints, *res;
int errcode;
char addrstr[100];
void *ptr;
memset (&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
if(use_canonname) {
hints.ai_flags = AI_CANONNAME;
}
errcode = getaddrinfo (host, NULL, &hints, &res);
printf("getaddrinfo returned %d: %s\n", errcode, gai_strerror(errcode));
if(errcode != 0) {
return -1;
}
printf ("Requested hostname: %s\n", host);
while(res) {
inet_ntop(res->ai_family, res->ai_addr->sa_data, addrstr, 100);
switch(res->ai_family) {
case AF_INET:
ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
break;
case AF_INET6:
ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
break;
}
inet_ntop(res->ai_family, ptr, addrstr, 100);
printf ("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4,
addrstr, res->ai_canonname);
res = res->ai_next;
}
return 0;
}
int main (int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "usage: %s hostname\n", argv[0]);
exit(1);
}
printf("looking up without no ai_flags set:\n");
lookup_host(argv[1], 0);
printf("\nlooking up with AI_CANONNAME flag set:\n");
lookup_host(argv[1], 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment