Skip to content

Instantly share code, notes, and snippets.

@WoZ WoZ/getaddrinfo.c
Created Mar 27, 2018

Embed
What would you like to do?
#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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.