1
0

resolveip.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Based on code found at https://dev.openwrt.org/ticket/4876 .
  3. * Extended by Jo-Philipp Wich <jo@mein.io> for use in OpenWrt.
  4. *
  5. * You may use this program under the terms of the GPLv2 license.
  6. */
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <sys/types.h>
  10. #include <sys/socket.h>
  11. #include <netdb.h>
  12. #include <arpa/inet.h>
  13. #include <netinet/in.h>
  14. #include <stdlib.h>
  15. #include <unistd.h>
  16. #include <signal.h>
  17. static void abort_query(int sig)
  18. {
  19. exit(1);
  20. }
  21. static void show_usage(void)
  22. {
  23. printf("Usage:\n");
  24. printf(" resolveip -h\n");
  25. printf(" resolveip [-t timeout] hostname\n");
  26. printf(" resolveip -4 [-t timeout] hostname\n");
  27. printf(" resolveip -6 [-t timeout] hostname\n");
  28. exit(255);
  29. }
  30. int main(int argc, char **argv)
  31. {
  32. int timeout = 3;
  33. int opt;
  34. char ipaddr[INET6_ADDRSTRLEN];
  35. void *addr;
  36. struct addrinfo *res, *rp;
  37. struct sigaction sa = { .sa_handler = &abort_query };
  38. struct addrinfo hints = {
  39. .ai_family = AF_UNSPEC,
  40. .ai_socktype = SOCK_STREAM,
  41. .ai_protocol = IPPROTO_TCP,
  42. .ai_flags = 0
  43. };
  44. while ((opt = getopt(argc, argv, "46t:h")) > -1)
  45. {
  46. switch ((char)opt)
  47. {
  48. case '4':
  49. hints.ai_family = AF_INET;
  50. break;
  51. case '6':
  52. hints.ai_family = AF_INET6;
  53. break;
  54. case 't':
  55. timeout = atoi(optarg);
  56. if (timeout <= 0)
  57. show_usage();
  58. break;
  59. case 'h':
  60. show_usage();
  61. break;
  62. }
  63. }
  64. if (!argv[optind])
  65. show_usage();
  66. sigaction(SIGALRM, &sa, NULL);
  67. alarm(timeout);
  68. if (getaddrinfo(argv[optind], NULL, &hints, &res))
  69. exit(2);
  70. for (rp = res; rp != NULL; rp = rp->ai_next)
  71. {
  72. addr = (rp->ai_family == AF_INET)
  73. ? (void *)&((struct sockaddr_in *)rp->ai_addr)->sin_addr
  74. : (void *)&((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr
  75. ;
  76. if (!inet_ntop(rp->ai_family, addr, ipaddr, INET6_ADDRSTRLEN - 1))
  77. exit(3);
  78. printf("%s\n", ipaddr);
  79. }
  80. freeaddrinfo(res);
  81. exit(0);
  82. }