5元组的哈希函数 - ipv4 / 6

时间:2015-03-25 14:43:36

标签: c networking hash hashtable

我正在为ipv4 / 6寻找一个有效的哈希函数(它可以是2个独立的函数,每个家族一个)

我遇到了这个问题:hash function for src dest ip + port

如何扩展它以支持ipv6?

由于

1 个答案:

答案 0 :(得分:1)

对于IPV4,我使用了以下功能:

uint32_t *S_block = ... 
// pointer to 1KB+ pre-defined random values.
// It can be reference to program code segment, or to long "help" string.
// For example, see: https://github.com/EvgenijM86/emercoin/blob/master/src/stun.cpp#L338

uint32_t HashIPV4(uint32_t x) {
  x += x >> 13;
  for(int i = 0; i < 7; i++)
    x += ((x << 11) | (x >> (32 - 11))) ^ S_block[(unsigned char)x];
  x += x >> 17;
  return x;
}

对于IPV6,您可以使用修改:

uint32_t HashIPV6(uint32_t *p) {
  x = 0x55555555;
  for(int i = 0; i < 28; i++) {
    x = ((x << 11) | (x >> (32 - 11))); 
    x += p[i & 3] ^ S_block[(unsigned char)x];
  }
  x += x >> 33;
  return x;
}