2
0

getaddrinfo.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. #include "test_helpers.h"
  10. int main(void) {
  11. struct addrinfo hints, *res;
  12. int errcode;
  13. char addrstr[INET6_ADDRSTRLEN];
  14. void *ptr;
  15. memset(&hints, 0, sizeof(hints));
  16. hints.ai_family = PF_UNSPEC;
  17. hints.ai_socktype = SOCK_STREAM;
  18. hints.ai_flags |= AI_CANONNAME;
  19. errcode = getaddrinfo("www.redox-os.org", NULL, &hints, &res);
  20. if (errcode != 0) {
  21. perror("getaddrinfo");
  22. exit(EXIT_FAILURE);
  23. }
  24. while (res) {
  25. switch (res->ai_family) {
  26. case AF_INET:
  27. ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
  28. break;
  29. case AF_INET6:
  30. ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
  31. break;
  32. }
  33. inet_ntop(res->ai_family, ptr, addrstr, INET6_ADDRSTRLEN);
  34. printf(
  35. "IPv%d address: %s (%s)\n",
  36. res->ai_family == AF_INET6 ? 6 : 4,
  37. addrstr,
  38. res->ai_canonname
  39. );
  40. res = res->ai_next;
  41. }
  42. }