addr_hash.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* hash table */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "addr_hash.h"
  6. #include "hash.h"
  7. #include "iftop.h"
  8. #define hash_table_size 256
  9. int compare(void* a, void* b) {
  10. addr_pair* aa = (addr_pair*)a;
  11. addr_pair* bb = (addr_pair*)b;
  12. if (aa->af != bb->af)
  13. return 0;
  14. if (aa->af == AF_INET6) {
  15. return (IN6_ARE_ADDR_EQUAL(&aa->src6, &bb->src6)
  16. && aa->src_port == bb->src_port
  17. && IN6_ARE_ADDR_EQUAL(&aa->dst6, &bb->dst6)
  18. && aa->dst_port == bb->dst_port
  19. && aa->protocol == bb->protocol);
  20. }
  21. /* AF_INET or unknown. */
  22. return (aa->src.s_addr == bb->src.s_addr
  23. && aa->src_port == bb->src_port
  24. && aa->dst.s_addr == bb->dst.s_addr
  25. && aa->dst_port == bb->dst_port
  26. && aa->protocol == bb->protocol);
  27. }
  28. static int __inline__ hash_uint32(uint32_t n) {
  29. return ((n & 0x000000FF)
  30. + ((n & 0x0000FF00) >> 8)
  31. + ((n & 0x00FF0000) >> 16)
  32. + ((n & 0xFF000000) >> 24));
  33. }
  34. int hash(void* key) {
  35. int hash;
  36. addr_pair* ap = (addr_pair*)key;
  37. if (ap->af == AF_INET6) {
  38. uint32_t* addr6 = (uint32_t*)ap->src6.s6_addr;
  39. hash = ( hash_uint32(addr6[0])
  40. + hash_uint32(addr6[1])
  41. + hash_uint32(addr6[2])
  42. + hash_uint32(addr6[3])
  43. + ap->src_port) % 0xFF;
  44. addr6 = (uint32_t*)ap->dst6.s6_addr;
  45. hash = ( hash + hash_uint32(addr6[0])
  46. + hash_uint32(addr6[1])
  47. + hash_uint32(addr6[2])
  48. + hash_uint32(addr6[3])
  49. + ap->dst_port) % 0xFF;
  50. } else {
  51. in_addr_t addr = ap->src.s_addr;
  52. hash = ( hash_uint32(addr)
  53. + ap->src_port) % 0xFF;
  54. addr = ap->dst.s_addr;
  55. hash = ( hash + hash_uint32(addr)
  56. + ap->dst_port) % 0xFF;
  57. }
  58. return hash;
  59. }
  60. void* copy_key(void* orig) {
  61. addr_pair* copy;
  62. copy = xmalloc(sizeof *copy);
  63. *copy = *(addr_pair*)orig;
  64. return copy;
  65. }
  66. void delete_key(void* key) {
  67. free(key);
  68. }
  69. /*
  70. * Allocate and return a hash
  71. */
  72. hash_type* addr_hash_create() {
  73. hash_type* hash_table;
  74. hash_table = xcalloc(hash_table_size, sizeof *hash_table);
  75. hash_table->size = hash_table_size;
  76. hash_table->compare = &compare;
  77. hash_table->hash = &hash;
  78. hash_table->delete_key = &delete_key;
  79. hash_table->copy_key = &copy_key;
  80. hash_initialise(hash_table);
  81. return hash_table;
  82. }