João Lourenço Mon Mar 12 18:40:52 -0400 2012

Subject: INET_ATON / INET_NTOA - php integer overload

The best way to store an IPv4 Address in a database is by converting it to longint, so we can easly sort, check if an ip address is on a range of network, etc.

In my case I have a mysql db with a column of type unsigned int(11). No problem reading from it and converting the number from longint to Internet address in dotted format. The problem is when trying to save it to a new address that overload max value o int (2147483647)

CREATE TABLE IF NOT EXISTS `testipaddrs` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ipaddress` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

class Testipaddr extends ActiveRecord\Model {
}

$host = Testipaddr::create(array('id'=>1,'ipaddress'=>ip2long('172.31.31.31')));
var_dump($host->ipaddress);
//int(-1407246561)

$host = Testipaddr::find_by_id(1);
var_dump($host->ipaddress);
//int(0)

The problem is well know and is related with PHP's integer type is signed, and many IP addresses will result in negative integers or 0 on 32-bit architectures.

So my question is simple (and don't want to change column cast int function :) ) Is there any way to force a model to use function (like mysql INET_ATON()/INET_NTOA() on a column, that convert the ip address to longint and back? Or is there any other solution?