addr_resolve.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <arpa/inet.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #ifdef __wasi__
  10. #include <wasi_socket_ext.h>
  11. #else
  12. #include <netdb.h>
  13. #endif
  14. int
  15. lookup_host(const char *host)
  16. {
  17. struct addrinfo hints, *res, *result;
  18. int errcode;
  19. char addrstr[100];
  20. void *ptr;
  21. memset(&hints, 0, sizeof(hints));
  22. hints.ai_family = AF_INET;
  23. hints.ai_socktype = SOCK_STREAM;
  24. errcode = getaddrinfo(host, NULL, &hints, &result);
  25. if (errcode != 0) {
  26. perror("getaddrinfo");
  27. return -1;
  28. }
  29. res = result;
  30. printf("Host: %s\n", host);
  31. while (res) {
  32. switch (res->ai_family) {
  33. case AF_INET:
  34. ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
  35. break;
  36. case AF_INET6:
  37. ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
  38. break;
  39. default:
  40. printf("Unsupported address family: %d\n", res->ai_family);
  41. continue;
  42. }
  43. inet_ntop(res->ai_family, ptr, addrstr, 100);
  44. printf("IPv%d address: %s (%s)\n", res->ai_family == AF_INET6 ? 6 : 4,
  45. addrstr, res->ai_socktype == SOCK_STREAM ? "TCP" : "UDP");
  46. res = res->ai_next;
  47. }
  48. freeaddrinfo(result);
  49. return EXIT_SUCCESS;
  50. }
  51. int
  52. main(int argc, char *argv[])
  53. {
  54. if (argc < 2) {
  55. printf("Usage: %s DOMAIN\n", argv[0]);
  56. return EXIT_FAILURE;
  57. }
  58. return lookup_host(argv[1]);
  59. }