getaddrinfo.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Adapted from https://gist.github.com/jirihnidek/bf7a2363e480491da72301b228b35d5d
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <netdb.h>
  6. #include <sys/types.h>
  7. #include <sys/socket.h>
  8. #include <arpa/inet.h>
  9. int main(void) {
  10. struct addrinfo hints, *res;
  11. int errcode;
  12. char addrstr[INET6_ADDRSTRLEN];
  13. void *ptr;
  14. memset(&hints, 0, sizeof(hints));
  15. hints.ai_family = PF_UNSPEC;
  16. hints.ai_socktype = SOCK_STREAM;
  17. hints.ai_flags |= AI_CANONNAME;
  18. errcode = getaddrinfo("www.redox-os.org", NULL, &hints, &res);
  19. if (errcode != 0) {
  20. perror("getaddrinfo");
  21. return EXIT_FAILURE;
  22. }
  23. while (res) {
  24. switch (res->ai_family) {
  25. case AF_INET:
  26. ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
  27. break;
  28. case AF_INET6:
  29. ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
  30. break;
  31. }
  32. inet_ntop(res->ai_family, ptr, addrstr, INET6_ADDRSTRLEN);
  33. printf(
  34. "IPv%d address: %s (%s)\n",
  35. res->ai_family == PF_INET6 ? 6 : 4,
  36. addrstr,
  37. res->ai_canonname
  38. );
  39. res = res->ai_next;
  40. }
  41. }