Find user location using Perl

March 11th, 2012
496 words · 3 minutes read · 0 Comments

The other day I finally put up a simple landing page for a project that I’m working on. The site itself is fairly bare, and doesn’t offer any features. It’s essentially the old “Under Construction” page, but with balls.

Rather than simply putting it out on the wild internet and forgetting it, I thought it would be interesting to log a few details about anyone who visits the page, to gather a few key demographics about people interested in the service such as their country and the time they spend browsing the site, among other things.

To find the users location, more specifically, the country and state that they are browsing from, I chose to use the Geo::IP module that I found on the CPAN.

It is essentially a wrapper for the MaxMind C API, which uses a database file of information gathered from ARIN, RIPE, APNIC, and LACNIC whois to map IP addresses to their geographical location.

It’s fairly simple to get up and running. Firstly however I would recommend installing the GeoIP C API - though there is a PurePerl version, which obviously will be a tad slower than it’s C counterpart.

After that, it was as simple as installing the Geo::IP module via CPAN, and writing a few lines of code.

Now, there is one more step which I may have overlooked - probably the most important, and that is to download the database file which provides the data on IP->Country translation. I’m using the free GeoLite Database for now, and it seems to be doing well for me so far, however there is a commercial alternative available via MaxMind’s website. The GeoLite database is updated monthly, whereas the paid alternative is updated weekly and, according to MaxMind, is a more accurate version of the GeoLite Database.

Anyway, now that we have everything we need, it’s a simple matter of opening ViM, or your text editor of choice, and getting on with those few lines of Perl that I mentioned earlier.

use Geo::IP;
my $ip = "";
my $gi = Geo::IP->open("/the/path/to/GeoLiteCity.dat", GEOIP_STANDARD);
my $record = $gi->record_by_address( $ip );

And hey presto! You will (read should) have a shiny new Geo::IP::Record object now, full of all the juicy information about the IP you’ve specified. To quickly dump this info out to your terminal screen I used the following, however you can now do with this data what you will.

$, = "\n";
print $record->country_code,

Exciting stuff? I know right.. Anyway, go have a look at the Geo::IP module on CPAN if this interests you to any degree, I highly recommend it.

Posted in: Tech
Tagged: code, perl
Originally published at:

Leave a comment