How to convert IP to Country location using Perl and Geo::IPfree

This config will provide you with a simple perl script which can be used to lookup country name from IP address. First we need to install libgeo-ipfree-perl perl library:

# apt-get install libgeo-ipfree-perl

Next, create a script eg. with a following code:

#!/usr/bin/env perl

use Geo::IPfree;

        my $geo = Geo::IPfree->new;
        my( $code, $country ) = $geo->LookUp( $ARGV[0] );

        print "Country: $country\n" . "Country Code: $code\n"

Make the script executable:

$ chmod +x

Our script accepts a single command line argument and that is the IP address we would like to convert/lookup to country name. For example we execute the script with an argument

Country: Italy
Country Code: IT

The above script can be used as a simple command line tool to convert IP address to a Country location or it can be also use for example to analyze Apache access.log and convert all IP addresses within to a country location:

$ for i in $( awk '{ print $1} ' access.log | sort | uniq ); do perl $i; done

Furthermore, perl’s Geo::IPfree library can also be used to lookup hostnames:

$ ./
Country: United States
Contry Code: US