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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With