Skip to content

Instantly share code, notes, and snippets.

@WoZ
Created March 27, 2018 09:50
Show Gist options
  • Save WoZ/70f90bc053d2718d6311682525430b72 to your computer and use it in GitHub Desktop.
Save WoZ/70f90bc053d2718d6311682525430b72 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: getaddrinfo <hostname>\n");
return 1;
}
printf("IP addresses for %s:\n\n", argv[1]);
int AI_FLAGS_TO_CHECK[5] = { AI_V4MAPPED, AI_V4MAPPED | AI_ALL, AI_ADDRCONFIG, AI_V4MAPPED | AI_ADDRCONFIG, AI_V4MAPPED | AI_ALL | AI_ADDRCONFIG };
int AI_FAMILY_TO_CHECK[3] = { AF_INET, AF_INET6, AF_UNSPEC };
int ai_flags, flag_no, ai_family, family_no;
for (family_no = 0; family_no < sizeof(AI_FAMILY_TO_CHECK) / sizeof(int); family_no++) {
for (flag_no = 0; flag_no < sizeof(AI_FLAGS_TO_CHECK) / sizeof(int); flag_no++) {
ai_family = AI_FAMILY_TO_CHECK[family_no];
if (ai_family == AF_INET) {
printf("[AF_INET] ");
} else if (ai_family == AF_INET6) {
printf("[AF_INET6] ");
} else if (ai_family == AF_UNSPEC) {
printf("[AF_UNSPEC] ");
} else {
fprintf(stderr, "Unknown family\n");
return 2;
}
ai_flags = AI_FLAGS_TO_CHECK[flag_no];
if (ai_flags & AI_V4MAPPED) {
printf("AI_V4MAPPED ");
}
if (ai_flags & AI_ALL) {
printf("AI_ALL ");
}
if (ai_flags & AI_ADDRCONFIG) {
printf("AI_ADDRCONFIG ");
}
printf("\n");
memset(&hints, 0, sizeof hints);
hints.ai_flags = ai_flags;
hints.ai_family = ai_family;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
continue;
//return 3;
}
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else if (p->ai_family == AF_INET6) {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
} else {
continue;
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res);
}
printf("--------------\n\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment