PHP inet_aton to store IP address in MySQL Database

Hold on Cowboy

This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.

Don’t store IP addresses in a database as a string like ( That is just the human readable form of that number. You want to store it in the database as an integer.

MySQL has built in functions to handle converting a dot-notation ip address to an integer equivalent.

` mysql> SELECT INET_ATON(‘’) AS ipn; +————+ | ipn | +————+ | 3232235530 | +————+

mysql> SELECT INET_NTOA(3232235530) AS ipa; +————–+ | ipa | +————–+ | | +————–+ ` But, I needed this type of functionality in PHP itself. Long story short, I’m using Doctrine to handle the relationship that PHP has to the database and I need to convert the human readable dot-notation IP address to the integer style (unsigned integer that is).

PHP’s built in function ip2long comes close, but there is a little bit more to work the magic.


$ip = long2ip(ip2long(“”)); print sprintf(“%u”, ip2long($ip));


is used to convert the signed integer to an unsigned one.

Ready to be inserted into the DB.