Storing IP Addresses in a Database
When it comes to storing IP addresses within a database you have several options.
Some people store IP addresses in a single field as DATATYPE VARCHAR in dotted decimal format.
IPfield: 192.168.1.0
Others break up the dotted decimal format into 4 quads and store each quad as DATATYPE VARCHAR , SMALLINT or TINYINT, in a separate field:
Quad1: 192
Quad2: 168
Quad3: 1
Quad4: 0
You could also store the data in binary.
The above options will certainly allow you to store your data, but with limited usability. At Country IP Blocks we prefer to store our IP network data in decimal format as DATATYPE INT UNSIGNED.
This allows us to store 192.168.1.0 as the integer 3232235776.
There are many benefits to storing your IP data as an integer. Integers are more easily searchable.
If your data gathering is nothing more than storing single IP addresses, then by all means store the data anyway you want. But, if you are looking to store data related to complete networks, consider storing your IP data in decimal format as DATATYPE INT UNSIGNED.
Storing your IP data in this manner makes it searchable and attributable. By searchable we mean more than locating an address. We mean identifying and attributing it to its specific network, country, region, etc. or locating it within a specific network (as is this address between address A and address B.
The question is how do we convert a dotted-decimal IP address into a decimal or integer address?
Converting from IP to decimal and decimal to IP is simple. It can be done several ways, but we generally prefer using MySQL functions to perform the conversions.
INET_ATON
Use INET_ATON to return the numeric value of an IP address: $ip = 192.168.1.0.
$query = “INSERT INTO iptable VALUES (”,inet_aton(‘$ip’)”; mysql_query($query);
INET_NTOA
Use INET_NTOA to return the IP address from a numeric value:
$query = (“SELECT inet_ntoa(ip) FROM iptable”); $results = mysql_query($query);
The above are examples on using INET_ATON and INET_NTOA to convert dotted decimal and integer formatted IP addresses.
In summation, you can store you IP addresses in a variety of ways, but for usability purposes we believe converting and storing your addresses in decimal will be more meaningful and useful.