addr_hash.c 1.55 KB
Newer Older
pdw's avatar
iftop  
pdw committed
1
2
3
4
5
6
/* hash table */

#include <stdio.h>
#include <stdlib.h>
#include "addr_hash.h"
#include "hash.h"
chris's avatar
""    
chris committed
7
#include "iftop.h"
pdw's avatar
iftop  
pdw committed
8
9
10
11
12
13
14

#define hash_table_size 256

int compare(void* a, void* b) {
    addr_pair* aa = (addr_pair*)a;
    addr_pair* bb = (addr_pair*)b;
    return (aa->src.s_addr == bb->src.s_addr 
pdw's avatar
pdw committed
15
16
17
            && aa->src_port == bb->src_port
            && aa->dst.s_addr == bb->dst.s_addr
            && aa->dst_port == bb->dst_port);
pdw's avatar
iftop  
pdw committed
18
19
20
21
22
23
24
25
26
27
28
29
}

int hash(void* key) {
    int hash;
    long addr;
    addr_pair* ap = (addr_pair*)key;
        
    addr = (long)ap->src.s_addr;

    hash = ((addr & 0x000000FF)
            + (addr & 0x0000FF00 >> 8)
            + (addr & 0x00FF0000 >> 16)
pdw's avatar
pdw committed
30
31
            + (addr & 0xFF000000 >> 24)
            + ap->src_port) % 0xFF;
pdw's avatar
iftop  
pdw committed
32
33

    addr = (long)ap->dst.s_addr;
pdw's avatar
pdw committed
34
    hash = ( hash + (addr & 0x000000FF)
pdw's avatar
iftop  
pdw committed
35
36
            + (addr & 0x0000FF00 >> 8)
            + (addr & 0x00FF0000 >> 16)
pdw's avatar
pdw committed
37
38
            + (addr & 0xFF000000 >> 24)
            + ap->dst_port) % 0xFF;
pdw's avatar
iftop  
pdw committed
39
40
41
42
43

    return hash;
}

void* copy_key(void* orig) {
chris's avatar
""    
chris committed
44
45
    addr_pair* copy;
    copy = xmalloc(sizeof *copy);
pdw's avatar
iftop  
pdw committed
46
47
48
49
50
51
52
53
54
55
56
57
58
    *copy = *(addr_pair*)orig;
    return copy;
}

void delete_key(void* key) {
    free(key);
}

/*
 * Allocate and return a hash
 */
hash_type* addr_hash_create() {
    hash_type* hash_table;
chris's avatar
""    
chris committed
59
    hash_table = xcalloc(hash_table_size, sizeof *hash_table);
pdw's avatar
iftop  
pdw committed
60
61
62
63
64
65
66
67
68
    hash_table->size = hash_table_size;
    hash_table->compare = &compare;
    hash_table->hash = &hash;
    hash_table->delete_key = &delete_key;
    hash_table->copy_key = &copy_key;
    hash_initialise(hash_table);
    return hash_table;
}