Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP compression for database storage

I have a database that stores the IP number of all users that have used a feature (ie: voted on a poll), and I want to avoid the same user or IP from voting twice.

As a result I have been storing all the IPs of the anonymous users that have voted on my polls. My database is filled with IPs like 123.456.789...

However, that is inefficient, is there a one way function that compresses and IP into a shorter string?

like 123.456.798 => %dA

like image 595
somid3 Avatar asked Jan 23 '26 08:01

somid3


1 Answers

For IPv4 you can compress an IP address into an int like this:

Scanner scanner = new Scanner(ip).useDelimiter("\\.");
int value = (scanner.nextInt() << 24) | (scanner.nextInt() << 16)
        | (scanner.nextInt() << 8) | scanner.nextInt();

This can be reversed too:

String ip = ((value >> 24) & 0xFF) + "." + ((value >> 16) & 0xFF)
        + "." + ((value >> 8) & 0xFF) + "." + (value & 0xFF);
like image 192
WhiteFang34 Avatar answered Jan 25 '26 22:01

WhiteFang34



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!