Storing IP Addresses

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
volomike
Forum Regular
Posts: 633
Joined: Wed Jan 16, 2008 9:04 am
Location: Myrtle Beach, South Carolina, USA

Storing IP Addresses

Post 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.
dml
Forum Contributor
Posts: 133
Joined: Sat Jan 26, 2008 2:20 pm

Re: Storing IP Addresses

Post 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.
Post Reply