2 #include <sys/socket.h>
5 #include <netinet/in.h>
22 static uint8_t toeplitz_key[KEYLEN];
23 static uint32_t hash_table[HASHLEN][256];
25 static void toeplitz_init(uint32_t[][256], int, const uint8_t[], int);
26 static void getaddrport(char *, uint32_t *, uint16_t *);
29 usage(const char *cmd)
31 fprintf(stderr, "%s [-s s1_hex [-s s2_hex]] [-p] [-m mask] [-d div] "
32 "addr1.port1 addr2.port2\n", cmd);
37 main(int argc, char *argv[])
39 uint32_t saddr, daddr;
40 uint16_t sport, dport;
41 uint32_t res, mask, divisor;
43 const char *cmd = argv[0];
44 uint8_t seeds[2] = { 0x6d, 0x5a };
52 while ((opt = getopt(argc, argv, "d:m:ps:")) != -1) {
55 divisor = strtoul(optarg, NULL, 10);
59 mask = strtoul(optarg, NULL, 16);
69 seeds[i++] = strtoul(optarg, NULL, 16);
82 for (i = 0; i < KEYLEN; ++i) {
84 toeplitz_key[i] = seeds[1];
86 toeplitz_key[i] = seeds[0];
89 getaddrport(argv[0], &saddr, &sport);
90 getaddrport(argv[1], &daddr, &dport);
92 toeplitz_init(hash_table, HASHLEN, toeplitz_key, KEYLEN);
94 res = hash_table[0][(saddr >> 0) & 0xff];
95 res ^= hash_table[1][(saddr >> 8) & 0xff];
96 res ^= hash_table[2][(saddr >> 16) & 0xff];
97 res ^= hash_table[3][(saddr >> 24) & 0xff];
98 res ^= hash_table[4][(daddr >> 0) & 0xff];
99 res ^= hash_table[5][(daddr >> 8) & 0xff];
100 res ^= hash_table[6][(daddr >> 16) & 0xff];
101 res ^= hash_table[7][(daddr >> 24) & 0xff];
103 res ^= hash_table[8][(sport >> 0) & 0xff];
104 res ^= hash_table[9][(sport >> 8) & 0xff];
105 res ^= hash_table[10][(dport >> 0) & 0xff];
106 res ^= hash_table[11][(dport >> 8) & 0xff];
109 printf("0x%08x, masked 0x%08x", res, res & mask);
113 printf(", modulo %u\n", (res & HASHMASK) % divisor);
118 toeplitz_init(uint32_t cache[][256], int cache_len,
119 const uint8_t key_str[], int key_strlen)
123 if (key_strlen < cache_len + (int)sizeof(uint32_t))
126 for (i = 0; i < cache_len; ++i) {
128 int j, b, shift, val;
130 bzero(key, sizeof(key));
133 * Calculate 32bit keys for one byte; one key for each bit.
135 for (b = 0; b < NBBY; ++b) {
136 for (j = 0; j < 32; ++j) {
140 bit = (i * NBBY) + b + j;
142 k = key_str[bit / NBBY];
143 shift = NBBY - (bit % NBBY) - 1;
144 if (k & (1 << shift))
145 key[b] |= 1 << (31 - j);
150 * Cache the results of all possible bit combination of
153 for (val = 0; val < 256; ++val) {
156 for (b = 0; b < NBBY; ++b) {
157 shift = NBBY - b - 1;
158 if (val & (1 << shift))
167 getaddrport(char *ap_str, uint32_t *addr, uint16_t *port0)
172 p = strrchr(ap_str, '.');
174 fprintf(stderr, "invalid addr.port %s\n", ap_str);
181 port = strtoul(p, NULL, 10);
182 *port0 = htons(port);
184 if (inet_pton(AF_INET, ap_str, addr) <= 0) {
185 fprintf(stderr, "invalid addr %s\n", ap_str);