Find by IP – Perl IP to location Example

In the next few lines we are going to describe a process of how to retrieve and geographical information from an IP address . For this we will use a MAxMind Perl API module. This company also provides a data file GeoLiteCity which is free but is less accurate than the paid version. As for a preparation part first we need to download a GeoIP perl module and data file:

$ cd
$ mkdir GeoIP
$ cd GeoIP
$ wget http://geolite.maxmind.com/download/geoip/api/perl/Geo-IP-1.38.tar.gz
$ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

While in the GeoIP directory the next step is to extract both packages:

$ tar xzf Geo-IP-1.38.tar.gz
$ gunzip GeoLiteCity.dat.gz

It should be pointed out that this article assumes that your are running some distribution of Linux with PERL interpreter.

At this stage create a file called IPtoLocation.pl in your GeoIP directory with a following code:

#!/usr/bin/perl 
 
use lib "Geo-IP-1.38/lib/";  
use Geo::IP; 
 
my $gi =   Geo::IP->open( "GeoLiteCity.dat", GEOIP_STANDARD ); 
 
   my $r = $gi->record_by_name($ARGV[0]); 
	 
   if ($r) { 
     print join( "\n", 
                 $r->country_code, $r->country_name, $r->city, 
                 $r->region,       $r->region_name,  $r->postal_code, 
                 $r->latitude,     $r->longitude,    $r->metro_code, 
                 $r->area_code ) 
       . "\n"; 
   } 
   else { 
     print "Location of this IP Address is NOT defined !\n"; 
   }

Make IPtoLocation.pl executable:

$ chmod +x IPtoLocation.pl

This simple Perl script accepts a single argument and that is an IP address we wish to convert to a Geographical location. In other words execute the script as below:

./IPtoLocation.pl 8.8.8.8

OUTPUT:

$ ./IPtoLocation.pl 8.8.8.8
US
United States
Mountain View
CA
California
94043
37.4192
-122.0574
807
650