I want to store IP addresses in my database, but I also need to use them throughout my application. I read about using INET_ATON()
and INET_NTOA()
There is an important distinction between ip2long
, long2ip
and the MySQL functions.
PHP's ip2long
and long2ip
deal with signed integers.
See http://php.net/manual/en/function.ip2long.php
"Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the '%u' formatter of sprintf() or printf() to get the string representation of the unsigned IP address."
MySQL's INET_ATON()
and INET_NTOA()
deal with unsigned integers
See http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton
"To store values generated by INET_ATON(), use an INT UNSIGNED column rather than INT, which is signed. If you use a signed column, values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly."
Here are some functions you can use to work between the two.
If you inserted into the MySQL database, an IP using INET_ATON()
, you can convert it back in PHP using the following:
long2ip(sprintf("%d", $ip_address));
And you can convert it to save it in the database from PHP using this:
sprintf("%u", ip2long($ip_address));
(Also important, don't type-cast the $ip_address
to int
as this might cause problems by wrapping the number if it's bigger than MAX_INT
. If you must cast it, cast it to a long
or float
)