Good hash function for IP addresses and remote ports

I am writing a peer application and I need a hash function to store IP / port pairs in a jash hashset. Instead of reinventing the wheel, I wondered if there are solutions out there, but google didn't bring much.

Can anyone recommend a hash function for IPv4 (bonus if it works for IPv6 too!) And the remote port number?

The port number will probably be the same if the client is not on the same host, in which case it will be sequential.


source to share

2 answers


pretty reasonable. I would just do this:

String ip; // if this is not a string, simply make it a string by + ""
int port;

int hash = (ip + "/" + port).hashCode();


It is "random" enough for coding purposes, so much so that most of the JDK API relies on it.

Remember this mantra ... "less code is good"




about as simple as you can get

this is pretty decent as the last few bits in the IP number are essentially random (ip assignment from ISP)

you can expand this with ip^port|port>>>16

to avoid the termination problem on all 0s or 1s to avoid

for IPv6 you will need ipv6_1^ipv6_2^ipv6_3^ipv6_4^port

(with ipv6_i

the i

th 32-bit part)

you can also do

int hash=17;
return hash



int hash=17;
return hash


as a standard hash function which is slightly better than standard xor because it is not commutative and you can change the order around if you are better off about it



All Articles