Skip to content

Instantly share code, notes, and snippets.

@nhooyr
Last active October 2, 2016 03:20
Show Gist options
  • Select an option

  • Save nhooyr/77a49419b6fcad38977c57004c48efff to your computer and use it in GitHub Desktop.

Select an option

Save nhooyr/77a49419b6fcad38977c57004c48efff to your computer and use it in GitHub Desktop.
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc < 2)
exit(1);
struct addrinfo* hints = calloc(0, sizeof(struct addrinfo));
hints->ai_socktype = SOCK_STREAM;
hints->ai_flags |= AI_CANONNAME;
struct addrinfo* res;
int ecode = getaddrinfo(argv[1], NULL, hints, &res) != 0;
if (ecode != 0) {
printf("error: %s\n", gai_strerror(ecode));
return ecode;
}
while (res) {
void* ptr;
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;
}
char addr[INET6_ADDRSTRLEN];
inet_ntop(res->ai_family, ptr, addr, sizeof(addr));
printf("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4,
addr, res->ai_canonname);
res = res->ai_next;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment