From 8b235297a596f3ddd6050994c845e2d7e22e72b2 Mon Sep 17 00:00:00 2001 From: Miroslav Lichvar Date: Mon, 23 Nov 2015 15:24:33 +0100 Subject: [PATCH] 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. --- ntp_sources.c | 20 +++++--------------- util.c | 28 ++++++++++++++++++++++++++++ util.h | 1 + 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/ntp_sources.c b/ntp_sources.c index eca681cc..e6ac8b0b 100644 --- a/ntp_sources.c +++ b/ntp_sources.c @@ -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++) { diff --git a/util.c b/util.c index fc3a81c3..da70f0bd 100644 --- a/util.c +++ b/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) { diff --git a/util.h b/util.h index f0cb6105..78b7d71a 100644 --- a/util.h +++ b/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); -- 2.47.2