DelphiFAQ Home Search:

Logging IP numbers in a perl script


commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.


I need to log IP numbers of computers connecting to our web site. I want to log them into a mysql database and do some analysis. Any pointers?


It is a good idea to convert the incoming IP number to a long integer e.g. IP would be converted to


Then keep a mysql table with IP ranges e.g. IP1 and IP2 each of type long int. This allows you to quickly find out which range a given IP falls into. The SQL would look like this:

select company_id from company_ip_ranges where ip1 <= $ip and $ip <= ip2

This gives you optimal performance. The downside is that the mysql table will be less readable by a human.

Unless you have a lot of traffic in a weak shared hosted environment, you may as well format the ip number by padding it with 0 (zeroes).

'' would be ''. The perl script below will do this padding for you.

The padded IP numbers can be compared just as long ints (only slightly slower, we're comparing 15 bytes instead of 4 bytes now), so the SQL to query the table is exactly the same.

sub format_ip {
   my ($ip) = @_;

   $ip =~ /(.*).(.*).(.*).(.*)/;
   my $a = $1;
   my $b = $2;
   my $c = $3;
   my $d = $4;
   return substr("000$a", -3) . '.' .
          substr("000$b", -3) . '.' .
          substr("000$c", -3) . '.' .
          substr("000$d", -3);


2012-11-12, 05:05:46
anonymous from United States  



NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: