INET_ATON() and INET_NTOA() in PHP?

blerh picture blerh · May 2, 2010 · Viewed 52k times · Source

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() in my MySQL queries to get a 32-bit unsigned integer out of an IP address, which is exactly what I want as it will make searching through the database faster than using char(15).

The thing is, I can't find a function that does the same sort of thing in PHP. The only thing I came across is:

http://php.net/manual/en/function.ip2long.php

So I tested it:

$ip = $_SERVER['REMOTE_ADDR'];
echo ip2long($ip);

And it outputs nothing. In the example they gave it seems to work, but then again I'm not exactly sure if ip2long() does the same thing as INET_ATON().

Does someone know a PHP function that will do this? Or even a completely new solution to storing an IP address in a database?

Thanks.

Answer

Pascal MARTIN picture Pascal MARTIN · May 2, 2010

The ip2long() and long2ip() functions should work just fine.

Note : you should use those for IPv4 addresses -- make sure that, in your case, $_SERVER['REMOTE_ADDR'] actually contains a valid IPv4 address (and not some IPv6-stuff).


Trying on a google IP address :

var_dump(ip2long('209.85.227.147'));
var_dump(long2ip(3512066963));

I get the following output :

int(3512066963)
string(14) "209.85.227.147"