Search code examples
javascriptjqueryhexipv4

How can I convert a dotted quad ipv4 ip address into a unique hex value / web color?


I know that in binary, an ipv4 address is 32 bits, and web colors are 24 bit. I also know because of that, there is not a unique color for every ip address.

I was able to hack together a solution by removing the first dotted quad, leaving a dotted triplet, and just using those for the R,G,B.

What I would prefer, and what I can't seem to wrap my head around right now is how to 'degrade' the 32 bit value into 24 bits, then get a hex value from that.

Does it even make sense to divide the decimal representation of an ipv4 address by 256, then convert that to hex?

I really hope that makes sense and I'm not abusing too much terminology.

Any programming language is fine, but bonus for javascript solution.


Solution

  • Pragmatic solution: Just create a quick to compute but hard to predict hash like MD5* from the IP address and use only the first 24 bits of the result.

    This will discard some of the entropy of the input, but there is as good as no bias for which bits are discarded. There will be collisions, but there will be no discernable pattern which addresses will collide.

    *yes, MD5 is obsolete as a cryptographic hash function, but this doesn't matter at all in this case. It's relatively easy to implement, executes quickly and creates seamingly chaotic results, and that's all that is needed in this case.