Skip to content

Instantly share code, notes, and snippets.

@kirs
Created January 11, 2020 18:42
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 kirs/f1472f6c553d2d628dd359c8dd2386b7 to your computer and use it in GitHub Desktop.
Save kirs/f1472f6c553d2d628dd359c8dd2386b7 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int i, ret;
struct gaicb *reqs[argc - 1];
char host[NI_MAXHOST];
struct addrinfo *res;
reqs[0] = malloc(sizeof(*reqs[0]));
memset(reqs[0], 0, sizeof(*reqs[0]));
reqs[0]->ar_name = NULL; // localhost
reqs[0]->ar_service = "http";
ret = getaddrinfo_a(GAI_WAIT, reqs, 1, NULL);
if (ret != 0) {
fprintf(stderr, "getaddrinfo_a() failed: %s\n",
gai_strerror(ret));
exit(EXIT_FAILURE);
}
struct gaicb const *wait_reqs[1];
wait_reqs[0] = reqs[0];
ret = gai_suspend(wait_reqs, 1, NULL);
// unless you replace this with if (ret && ret != EAI_ALLDONE),
// it will always fail with EAI_ALLDONE because resolving localhost is fast
// by the time gai_suspend is called, the address is already resolved.
if (ret) {
printf("gai_suspend(): %s\n", gai_strerror(ret));
return 1;
}
printf("%s: ", reqs[0]->ar_name);
ret = gai_error(reqs[0]);
if (ret == 0) {
res = reqs[0]->ar_result;
ret = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof(host),
NULL, 0, NI_NUMERICHOST);
if (ret != 0) {
fprintf(stderr, "getnameinfo() failed: %s\n",
gai_strerror(ret));
exit(EXIT_FAILURE);
}
puts(host);
} else {
puts(gai_strerror(ret));
}
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment