Created
May 23, 2017 23:38
-
-
Save vivkin/bc7cd6ede2c19d135b16e7f578d2c305 to your computer and use it in GitHub Desktop.
show getaddrinfo(3) results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <arpa/inet.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
int main(int argc, char **argv) { | |
const char *hostname = NULL; | |
const char *servname = NULL; | |
struct addrinfo hints, *res; | |
memset(&hints, 0, sizeof(hints)); | |
for (char ch; (ch = getopt(argc, argv, "46f:h:s:tu")) != -1;) { | |
// clang-format off | |
switch (ch) { | |
case '4': hints.ai_family = AF_INET; break; | |
case '6': hints.ai_family = AF_INET6; break; | |
case 'f': | |
#define AI_(f) if (!strcmp(#f, optarg)) hints.ai_flags |= AI_##f; else | |
AI_(ALL) | |
AI_(CANONNAME) | |
AI_(DEFAULT) | |
AI_(NUMERICHOST) | |
AI_(NUMERICSERV) | |
AI_(PASSIVE) | |
AI_(V4MAPPED) | |
#undef AI_ | |
fprintf(stderr, "%s: unknown flag -- %s\n", argv[0], optarg); | |
break; | |
case 'h': hostname = optarg; break; | |
case 's': servname = optarg; break; | |
case 't': hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; break; | |
case 'u': hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; break; | |
case '?': | |
default: | |
fprintf(stderr, "usage: %s [-46tu] [-f ALL|CANONNAME|DEFAULT|NUMERICHOST|NUMERICSERV|PASSIVE|V4MAPPED] [-h hostname] [-s servname]\n", argv[0]); | |
exit(EXIT_FAILURE); | |
} | |
// clang-format on | |
} | |
int error = getaddrinfo(hostname, servname, &hints, &res); | |
if (error) { | |
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error)); | |
exit(EXIT_FAILURE); | |
} | |
for (struct addrinfo *p = res; p != NULL; p = p->ai_next) { | |
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; | |
if (getnameinfo(p->ai_addr, p->ai_addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) { | |
fprintf(stderr, "could not get numeric hostname"); | |
exit(EXIT_FAILURE); | |
} | |
printf("%s%s\t%s\t%s\n", | |
p->ai_protocol == IPPROTO_TCP ? "tcp" : "udp", | |
p->ai_family == AF_INET ? "4" : "6", | |
hbuf, sbuf); | |
} | |
freeaddrinfo(res); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment