Search code examples
javaalgorithmhaship-addressipv4

Mapping Address to unique number


What is the best way to make a unique number from the IP Address?

19.22.145.103

I was planning to sum each octet to get unique number but it looks like I might not get a unique number for each IP Address.

Sum of each octet 19 + 22 + 145 + 103 = 289 as the unique number.

I already know that we can't map IPv4 to 16 bit so solution with less collisions are acceptable. I am looking for both the solution as mentioned in below two points.

  • Firstly what is the best way to get unique number by storing it in 32 bit datatype?
  • Secondly now problem is I need to store this unique number in short data type. Since short is 16 bit so we might not be able to map IPv4 to short uniquely. Is there any other way we can come up which will have less collisions if we still use short datatype instead of using sum of each octet as I was using above?

All my IP Addresses starts with 10. if helps in deciding the algorithm so there will be fewer collisions.


Solution

  • https://en.wikipedia.org/wiki/Hash_function

    Make hash function, then cut it to the size of short. For example :

    (or some other prime numbers) ( 7 ^ 19 + 5 * 22 + 11 * 145 + 17 * 103 ) % size_of_short