Joe Morano
Joe Morano

Reputation: 1895

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?

Upvotes: 4

Views: 2885

Answers (2)

Chris Trudeau
Chris Trudeau

Reputation: 1437

In the way you described it would be impossible to "re-IP" it because you wouldn't know where to put the periods back. Could be 127.0.0.1 or 12.70.0.1 etc. You could use four separate columns for each of the sections and the integer size would only have to be 9 or 8 unsigned to represent 0-255 if you're that concerned about space.

Then put them together ip_col_1+".".ip_col_2+"."+ip_col_3+"."+ip_col_4 to actually use it.

I can't really think of this making much of a difference except making your code more complex, as the comments mentioned.

Upvotes: 1

Casper
Casper

Reputation: 34318

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/

Upvotes: 9

Related Questions