Page 1 of 1

Storing IP Addresses

Posted: Thu Jun 19, 2008 7:10 pm
by volomike
I recently saw this example on the web for storing IP addresses in a database:

http://arjen-lentz.livejournal.com/44290.html

The problem with that, however, is that it doesn't account for IPv6, which I think is just around the corner here with the rate of Chinese and Indian systems coming online so rapidly these days.

The reason I need to store this is because my client does fraud checks and wants to mark bad IP addresses where people goof with the forms on his site, or try to get more cash out of the system than they are allowed, etc. Every login, unfortunately, will have to go through an IP scan. We will log and block any one deemed a bad guy.

So, some questions:

1. Do you know a routine that is IPv4 and IPv6 and uses the least amount of space and processor time with the database and PHP?

2. Is it just better to store the IPv4/IPv6 in the database as is?

Remember -- I'm talking a database that may have a few hundred thousand members, and a site that may have nearly a 6,000 - 10,000 page hits a day among the whole site's set of pages.

Re: Storing IP Addresses

Posted: Thu Jun 19, 2008 8:27 pm
by dml
I'm not familiar with IPv6, but it looks like it's a question of packing a 128 bit address into the database. That would mean a column type of binary(16). You can use pack() to convert from the hex address into a 16 byte string to store in the database.

Code: Select all

 
function pack_ipv6($address){
  return pack("H*", str_replace(":", "", $address));
}
$address =  "2001:0db8:3c4d:0015:0000:0000:abcd:ef12";
$packed_address = pack_ipv6($address);
echo bin2hex($packed_address), "\n";
 
It's worth doing: not only saves disc space, but if you're checking for matching addresses on every request, you'll have to index the column, and the indexes are likely to be cached in memory, so the less space they take up the better.