views:

492

answers:

3

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.

+5  A: 

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" 
Pascal MARTIN
+1  A: 

ip2long is equivalent to inet_aton().

ip2long only works with IPv4. I suspect your system is using IPv6 for loopback. Try to print REMOTE_ADDR.

ZZ Coder
Ah I can see why it isn't working now, `$_SERVER['REMOTE_ADDR']` returns: `::1`. Probably because I'm on localhost. Is there a way to prevent this? Or must I do a check to see if it's returning `::1`?
blerh
::1 is the IPv6 for loopback. You need to disable IPv6. For Linux, follow this instruction: http://blog.taragana.com/index.php/archive/how-to-disable-ipv6-on-fedora-linux-why/
ZZ Coder
A: 

For IPv4 and IPv6 support use inet_pton() and inet_ntop(), these are availiable since PHP 5.1+ and mimic exactly the equivalent MySQL functions.

Otherwise just use ip2long() and long2ip().

Alix Axel