Best way to store IP addresses in MySQL

It’s tempting to store IP addresses in a database as a VARCHAR(15) in the absence of a dedicated IP address field type in mysql, but that isn’t the most efficient way of doing so. The best way that I’ve come across to store an IPv4 address is to store it as an unsigned integer. In phpmyadmin you might set up an ip address field so that it looks something like:

You’ll realise I’m sure that you can’t just add the dotted IP address straight into an INT field without first converting it into a valid format. For that you’ll need a PHP function called ip2long which will convert a string containing an IP dotted address into a integer that can be stored in the INT field.

Here is a quick example of how you might go about getting the real IP address of a client and then storing and retrieving its value from the mysql DB:

//Test if it is a shared client

if (!empty($_SERVER['HTTP_CLIENT_IP'])){
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//The value of $ip at this point would look something like: ""
$ip = ip2long($ip);
//The $ip would now look something like: 1073732954

Now that you have the real IP address of the client converted to the INT format, you can write it into the DB as you normally would:

$sql = "INSERT INTO user(ip) VALUES('$ip')";
$dbQuery = mysql_query($sql,$dbLink);

To retrieve the original IP address from the database you can use the mysql function INET_NTOA like so:


Alternately you could use the PHP function long2ip to convert the returned INT value into the dotted IPv4 address in the PHP code instead, and you could even add the dotted IP address to the INT field in the db using the mysql funtion INET_ATON.

Storing IP addresses in this manner is beneficial because it takes less space than storing it as a string. The other benefit is that lookups are faster because integer comparisons are quicker than string comparisons.


About 智足者富


电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>