[go: up one dir, main page]

Menu

[r7]: / routing / dhash.h  Maximize  Restore  History

Download this file

56 lines (41 with data), 1.1 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef __DHASH_H__
#define __DHASH_H__
#include <openssl/sha.h>
#include <algorithm>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
class CDHash
{
public:
CDHash(): m_im(32) {}
CDHash(const int m): m_im(m) {}
~CDHash() {}
unsigned int hash(const char* str)
{
unsigned char res[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)str, strlen(str), res);
return *(unsigned int*)(res + SHA_DIGEST_LENGTH - 4);
}
unsigned int hash(const in_addr& ip)
{
char tmp[16];
return hash(inet_ntop(AF_INET, &ip, tmp, 16));
}
static unsigned int hash(const char* str, int m)
{
unsigned char res[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)str, strlen(str), res);
return (*(unsigned int*)(res + SHA_DIGEST_LENGTH - 4)) & (int(pow(2, double(m))) - 1);
}
static unsigned int hash(const in_addr& ip, int m)
{
char tmp[16];
return CDHash::hash(inet_ntop(AF_INET, &ip, tmp, 16), m);
}
private:
unsigned int m_im;
};
#endif