util: add function for IP address hashing
Move the hashing function from find_slot() in ntp_sources to make it available to clientlog and improve the hashing a bit.
This commit is contained in:
parent
59a3140621
commit
8b235297a5
3 changed files with 34 additions and 15 deletions
|
@ -202,26 +202,16 @@ find_slot(NTP_Remote_Address *remote_addr, int *slot, int *found)
|
|||
uint32_t hash;
|
||||
unsigned int i, size;
|
||||
unsigned short port;
|
||||
uint8_t *ip6;
|
||||
|
||||
size = ARR_GetSize(records);
|
||||
|
||||
switch (remote_addr->ip_addr.family) {
|
||||
case IPADDR_INET6:
|
||||
ip6 = remote_addr->ip_addr.addr.in6;
|
||||
hash = (ip6[0] ^ ip6[4] ^ ip6[8] ^ ip6[12]) |
|
||||
(ip6[1] ^ ip6[5] ^ ip6[9] ^ ip6[13]) << 8 |
|
||||
(ip6[2] ^ ip6[6] ^ ip6[10] ^ ip6[14]) << 16 |
|
||||
(ip6[3] ^ ip6[7] ^ ip6[11] ^ ip6[15]) << 24;
|
||||
break;
|
||||
case IPADDR_INET4:
|
||||
hash = remote_addr->ip_addr.addr.in4;
|
||||
break;
|
||||
default:
|
||||
*found = *slot = 0;
|
||||
return;
|
||||
if (remote_addr->ip_addr.family != IPADDR_INET4 &&
|
||||
remote_addr->ip_addr.family != IPADDR_INET6) {
|
||||
*found = *slot = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
hash = UTI_IPToHash(&remote_addr->ip_addr);
|
||||
port = remote_addr->port;
|
||||
|
||||
for (i = 0; i < size / 2; i++) {
|
||||
|
|
28
util.c
28
util.c
|
@ -359,6 +359,34 @@ UTI_IPToRefid(IPAddr *ip)
|
|||
|
||||
/* ================================================== */
|
||||
|
||||
uint32_t
|
||||
UTI_IPToHash(IPAddr *ip)
|
||||
{
|
||||
unsigned char *addr;
|
||||
unsigned int i, len;
|
||||
uint32_t hash;
|
||||
|
||||
switch (ip->family) {
|
||||
case IPADDR_INET4:
|
||||
addr = (unsigned char *)&ip->addr.in4;
|
||||
len = sizeof (ip->addr.in4);
|
||||
break;
|
||||
case IPADDR_INET6:
|
||||
addr = ip->addr.in6;
|
||||
len = sizeof (ip->addr.in6);
|
||||
break;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = 0, hash = 0; i < len; i++)
|
||||
hash = 71 * hash + addr[i];
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* ================================================== */
|
||||
|
||||
void
|
||||
UTI_IPHostToNetwork(IPAddr *src, IPAddr *dest)
|
||||
{
|
||||
|
|
1
util.h
1
util.h
|
@ -82,6 +82,7 @@ extern char *UTI_IPToString(IPAddr *ip);
|
|||
|
||||
extern int UTI_StringToIP(const char *addr, IPAddr *ip);
|
||||
extern uint32_t UTI_IPToRefid(IPAddr *ip);
|
||||
extern uint32_t UTI_IPToHash(IPAddr *ip);
|
||||
extern void UTI_IPHostToNetwork(IPAddr *src, IPAddr *dest);
|
||||
extern void UTI_IPNetworkToHost(IPAddr *src, IPAddr *dest);
|
||||
extern int UTI_CompareIPs(IPAddr *a, IPAddr *b, IPAddr *mask);
|
||||
|
|
Loading…
Reference in a new issue