DelphiFAQ Home Search:
General :: Web publishing :: perl CGI
CGI = Common Gateway Interface, a specification for transferring information between a web server and a CGI program. Here you find code snippets for CGIs written in perl.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Logging IP numbers in a perl script

Question:

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?

Answer:

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

(((1*256)+2)*256)+3)*256+4

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).

'1.2.3.4' would be '001.002.003.004'. 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);
 }
 

Generated 12:02:17 on May 24, 2017