Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store IP addresses as integers?

I record the IP address of users. Since IP addresses include periods, I'm storing them as strings. But I'd like to try to save space on my server by trying to save them as integers.

I considered doing this:

@user_ip = request.remote_ip.delete(".").to_i

Which would convert, for example, "127.0.0.1" to 127001.

But I'm concerned two different IP addresses could be saved as the same integer under that method.

Is that possible? If so, is there a better way to save IP addresses as integers?

like image 872
Joe Morano Avatar asked Dec 24 '22 12:12

Joe Morano


1 Answers

The standard way to do these conversions (in C-language) is called inet_aton (ascii to number) and inet_ntoa (number to ascii). The Ruby equivalent methods are included in IPAddr:

require 'ipaddr'

IPAddr.new("192.168.0.1").to_i
 => 3232235521 

IPAddr.new(3232235521, Socket::AF_INET).to_s
 => "192.168.0.1" 

But as others pointer out here too, querying the number representations from a database is not always practical. However MySQL for example does allow you to use the inet_ntoa/aton functions directly in queries:
http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html

This is useful if you want to start to filter and query IP addresses with netmasks for instance. See here for more examples how to set it up and how to run queries this way:
http://www.finnie.org/2007/12/05/mysql-and-cidr-selection/

like image 137
Casper Avatar answered Jan 02 '23 15:01

Casper