24 May 2011

Getting IP location (city, country) using perl Geo::IP

Geo::IP module a simple file-based database. This database simply contains IP blocks as keys, and countries as values.  The data contains all public IP addresses and should be more complete and accurate than reverse DNS lookups. This module can be used to automatically select the geographically closest mirror, or to analyze your web server logs, or to determine the countries of your visitors.

To find a country for an IP address, this module uses the database contained in /usr/local/share/GeoIP/GeoIP.dat to find a Network that contains the IP address.

Installing Geo::IP module:

# wget http://www.maxmind.com/download/geoip/database/GeoIP.dat.gz
# gunzip GeoIP.dat.gz
# mv GeoIP.dat /usr/local/share/GeoIP/GeoIP.dat

Download Geo-IP-PurePerl-1.17.tar from
now extract it using
# tar -xvf Geo-IP-PurePerl-1.17.tar

now install the module using following the steps
# perl Makefile.PL
# make
# make test
# make install

Sample Code to get IP to location:
use strict;

use Geo::IP::PurePerl;
my $addr = shift;

my $gi = Geo::IP::PurePerl->new("/usr/local/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD);

if ($addr){
  my ($country_code,
          $area_code) = $gi->get_city_record($addr);

  print $country_code  . "\n";
  print $country_code3 . "\n";
  print $country_name  . "\n";
  print $region        . "\n";
  print $city          . "\n";
  print $postal_code   . "\n";
  print $latitude      . "\n";
  print $longitude     . "\n";
  print $dma_code      . "\n";
  print $area_code     . "\n";
} else {
  print STDERR "Usage: $0 ipaddr\n";

save it as ipdetails.pl
#chmod +x ipdetails.pl

run the script
# ./ipdetails.pl

sample output:


1 comment:

  1. Trace IP Address with IP Address Locator such as Country, City, longitude, latitude and more.