ns_hash.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* hash table */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in_systm.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. #include "ns_hash.h"
  11. #include "hash.h"
  12. #include "iftop.h"
  13. #define hash_table_size 256
  14. int ns_hash_compare(void* a, void* b) {
  15. struct in6_addr* aa = (struct in6_addr*)a;
  16. struct in6_addr* bb = (struct in6_addr*)b;
  17. return IN6_ARE_ADDR_EQUAL(aa, bb);
  18. }
  19. static int __inline__ hash_uint32(uint32_t n) {
  20. return ((n & 0x000000FF)
  21. + ((n & 0x0000FF00) >> 8)
  22. + ((n & 0x00FF0000) >> 16)
  23. + ((n & 0xFF000000) >> 24));
  24. }
  25. int ns_hash_hash(void* key) {
  26. int hash;
  27. uint32_t* addr6 = (uint32_t*)((struct in6_addr *) key)->s6_addr;
  28. hash = ( hash_uint32(addr6[0])
  29. + hash_uint32(addr6[1])
  30. + hash_uint32(addr6[2])
  31. + hash_uint32(addr6[3])) % 0xFF;
  32. return hash;
  33. }
  34. void* ns_hash_copy_key(void* orig) {
  35. struct in6_addr* copy;
  36. copy = xmalloc(sizeof *copy);
  37. memcpy(copy, orig, sizeof *copy);
  38. return copy;
  39. }
  40. void ns_hash_delete_key(void* key) {
  41. free(key);
  42. }
  43. /*
  44. * Allocate and return a hash
  45. */
  46. hash_type* ns_hash_create() {
  47. hash_type* hash_table;
  48. hash_table = xcalloc(hash_table_size, sizeof *hash_table);
  49. hash_table->size = hash_table_size;
  50. hash_table->compare = &ns_hash_compare;
  51. hash_table->hash = &ns_hash_hash;
  52. hash_table->delete_key = &ns_hash_delete_key;
  53. hash_table->copy_key = &ns_hash_copy_key;
  54. hash_initialise(hash_table);
  55. return hash_table;
  56. }