testdns.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include "stx.h"
  2. #include <netinet/in.h>
  3. #include <arpa/inet.h>
  4. #define MAX_ADDRS 128
  5. #define TIMEOUT (4*1000000LL)
  6. static void do_resolve(const char *host)
  7. {
  8. struct in_addr addrs[MAX_ADDRS];
  9. int i, n = MAX_ADDRS;
  10. if (stx_dns_getaddrlist(host, addrs, &n, TIMEOUT) < 0) {
  11. fprintf(stderr, "stx_dns_getaddrlist: can't resolve %s: ", host);
  12. if (h_errno == NETDB_INTERNAL)
  13. perror("");
  14. else
  15. herror("");
  16. } else {
  17. if (n > 0)
  18. printf("%-40s %s\n", (char *)host, inet_ntoa(addrs[0]));
  19. for (i = 1; i < n; i++)
  20. printf("%-40s %s\n", "", inet_ntoa(addrs[i]));
  21. }
  22. }
  23. static void show_info(void)
  24. {
  25. stx_cache_info_t info;
  26. stx_dns_cache_getinfo(&info);
  27. printf("DNS cache info:\n\n");
  28. printf("max_size: %8d\n", (int)info.max_size);
  29. printf("capacity: %8d bytes\n", (int)info.max_weight);
  30. printf("hash_size: %8d\n", (int)info.hash_size);
  31. printf("cur_size: %8d\n"
  32. "cur_mem: %8d bytes\n"
  33. "hits: %8d\n"
  34. "lookups: %8d\n"
  35. "inserts: %8d\n"
  36. "deletes: %8d\n",
  37. (int)info.cur_size, (int)info.cur_weight, (int)info.hits,
  38. (int)info.lookups, (int)info.inserts, (int)info.deletes);
  39. }
  40. extern stx_cache_t *_stx_dns_cache;
  41. static void printhost(void *host, void *data)
  42. {
  43. printf("%s\n", (char *)host);
  44. }
  45. static void show_lru(void)
  46. {
  47. printf("LRU hosts:\n\n");
  48. stx_cache_traverse_lru(_stx_dns_cache, printhost, 10);
  49. }
  50. static void show_mru(void)
  51. {
  52. printf("MRU hosts:\n\n");
  53. stx_cache_traverse_mru(_stx_dns_cache, printhost, 10);
  54. }
  55. static void flush_cache(void)
  56. {
  57. stx_cache_empty(_stx_dns_cache);
  58. printf("DNS cache is empty\n");
  59. }
  60. int main()
  61. {
  62. char line[256];
  63. char str[sizeof(line)];
  64. st_init();
  65. stx_dns_cache_init(100, 10000, 101);
  66. for ( ; ; ) {
  67. fputs("> ", stdout);
  68. fflush(stdout);
  69. if (!fgets(line, sizeof(line), stdin))
  70. break;
  71. if (sscanf(line, "%s", str) != 1)
  72. continue;
  73. if (strcmp(str, "exit") == 0 || strcmp(str, "quit") == 0)
  74. break;
  75. if (strcmp(str, "info") == 0) {
  76. show_info();
  77. continue;
  78. }
  79. if (strcmp(str, "lru") == 0) {
  80. show_lru();
  81. continue;
  82. }
  83. if (strcmp(str, "mru") == 0) {
  84. show_mru();
  85. continue;
  86. }
  87. if (strcmp(str, "flush") == 0) {
  88. flush_cache();
  89. continue;
  90. }
  91. do_resolve(str);
  92. }
  93. return 0;
  94. }