nslookup.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (C) 2023 Amazon.com Inc. or its affiliates. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <assert.h>
  6. #include <errno.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <pthread.h>
  10. #ifdef __wasi__
  11. #include <wasi/api.h>
  12. #include <sys/socket.h>
  13. #include <netinet/in.h>
  14. #include <wasi_socket_ext.h>
  15. #else
  16. #include <netdb.h>
  17. #endif
  18. void
  19. test_nslookup(int af)
  20. {
  21. struct addrinfo *res;
  22. int count = 0;
  23. struct addrinfo hints;
  24. char *url = "google-public-dns-a.google.com";
  25. memset(&hints, 0, sizeof(hints));
  26. hints.ai_family = af;
  27. hints.ai_socktype = SOCK_STREAM;
  28. int ret = getaddrinfo(url, 0, &hints, &res);
  29. if (ret != 0) {
  30. if (ret == EAI_SYSTEM) {
  31. fprintf(stderr, "getaddrinfo failed: %s (%s)\n", gai_strerror(ret),
  32. strerror(errno));
  33. }
  34. else {
  35. fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(ret));
  36. }
  37. }
  38. assert(ret == 0);
  39. struct addrinfo *address = res;
  40. while (address) {
  41. assert(address->ai_family == af);
  42. assert(address->ai_socktype == SOCK_STREAM);
  43. count++;
  44. address = address->ai_next;
  45. }
  46. assert(count > 0);
  47. freeaddrinfo(res);
  48. }
  49. void *
  50. test_nslookup_mt(void *params)
  51. {
  52. int *af = (int *)params;
  53. test_nslookup(*af);
  54. return NULL;
  55. }
  56. int
  57. main()
  58. {
  59. int afs[] = { AF_INET, AF_INET6 };
  60. for (int i = 0; i < sizeof(afs) / sizeof(afs[0]); i++) {
  61. pthread_t th;
  62. printf("Testing %d in main thread...\n", afs[i]);
  63. test_nslookup(afs[i]);
  64. printf("Testing %d in a new thread...\n", afs[i]);
  65. pthread_create(&th, NULL, test_nslookup_mt, &afs[i]);
  66. pthread_join(th, NULL);
  67. }
  68. return 0;
  69. }