perl CGI (3)
Logging IP numbers in a perl script
This article has not been rated yet. After reading, feel free to leave comments and rate it.
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 184.108.40.206 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).
'220.127.116.11' 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.