You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

getaddrinfodnstest.c 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netdb.h> /* getaddrinfo, getnameinfo */
  4. #include <stdio.h> /* fprintf, printf */
  5. #include <stdlib.h> /* exit */
  6. #include <string.h> /* memset */
  7. int
  8. getaddrinfodnsresolution(char *domain)
  9. {
  10. struct addrinfo hints, *res, *res0;
  11. int error;
  12. char host[NI_MAXHOST];
  13. /*
  14. * Request only one socket type from getaddrinfo(). Else we
  15. * would get both SOCK_DGRAM and SOCK_STREAM, and print two
  16. * copies of each numeric address.
  17. */
  18. memset(&hints, 0, sizeof hints);
  19. hints.ai_family = PF_UNSPEC; /* IPv4, IPv6, or anything */
  20. hints.ai_socktype = SOCK_DGRAM; /* Dummy socket type */
  21. /*
  22. * Use getaddrinfo() to resolve domain and allocate
  23. * a linked list of addresses.
  24. */
  25. error = getaddrinfo(domain, NULL, &hints, &res0);
  26. if (error) {
  27. fprintf(stderr, "%s\n", gai_strerror(error));
  28. exit(1);
  29. }
  30. /* Iterate the linked list. */
  31. for (res = res0; res; res = res->ai_next) {
  32. /*
  33. * Use getnameinfo() to convert res->ai_addr to a
  34. * printable string.
  35. *
  36. * NI_NUMERICHOST means to present the numeric address
  37. * without doing reverse DNS to get a domain name.
  38. */
  39. error = getnameinfo(res->ai_addr, res->ai_addrlen,
  40. host, sizeof host, NULL, 0, NI_NUMERICHOST);
  41. if (error) {
  42. fprintf(stderr, "%s\n", gai_strerror(error));
  43. } else {
  44. /* Print the numeric address. */
  45. printf("%s\n", host);
  46. }
  47. }
  48. /* Free the linked list. */
  49. freeaddrinfo(res0);
  50. return 0;
  51. }