serv_hash.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* hash table */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <netdb.h>
  5. #include "serv_hash.h"
  6. #include "hash.h"
  7. #include "iftop.h"
  8. // Deliberately not a power of 2 or 10
  9. #define hash_table_size 123
  10. int serv_hash_compare(void* a, void* b) {
  11. ip_service* aa = (ip_service*)a;
  12. ip_service* bb = (ip_service*)b;
  13. return (aa->port == bb->port &&
  14. aa->protocol == bb->protocol);
  15. }
  16. int serv_hash_hash(void* key) {
  17. ip_service* serv = (ip_service*)key;
  18. return serv->protocol % hash_table_size;
  19. }
  20. void* serv_hash_copy_key(void* orig) {
  21. ip_service* copy;
  22. copy = xmalloc(sizeof *copy);
  23. *copy = *(ip_service*)orig;
  24. return copy;
  25. }
  26. void serv_hash_delete_key(void* key) {
  27. free(key);
  28. }
  29. /*
  30. * Allocate and return a hash
  31. */
  32. hash_type* serv_hash_create() {
  33. hash_type* hash_table;
  34. hash_table = xcalloc(hash_table_size, sizeof *hash_table);
  35. hash_table->size = hash_table_size;
  36. hash_table->compare = &serv_hash_compare;
  37. hash_table->hash = &serv_hash_hash;
  38. hash_table->delete_key = &serv_hash_delete_key;
  39. hash_table->copy_key = &serv_hash_copy_key;
  40. hash_initialise(hash_table);
  41. return hash_table;
  42. }
  43. void serv_hash_initialise(hash_type* sh) {
  44. struct servent* ent;
  45. struct protoent* pent;
  46. ip_service* service;
  47. setprotoent(1);
  48. while((ent = getservent()) != NULL) {
  49. pent = getprotobyname(ent->s_proto);
  50. if(pent != NULL) {
  51. service = xmalloc(sizeof(ip_service));
  52. service->port = ntohs(ent->s_port);
  53. service->protocol = pent->p_proto;
  54. hash_insert(sh, service, xstrdup(ent->s_name));
  55. }
  56. }
  57. endprotoent();
  58. }