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
http://geolite.maxmind.com/download/geoip/api/pureperl/
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:
#!/usr/bin/perl
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,
          $country_code3,
          $country_name,
          $region,$city,
          $postal_code,
          $latitude,
          $longitude,
          $dma_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";
  exit;
}


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


run the script
# ./ipdetails.pl 122.177.211.119

sample output:
IN
IND
India
07
Delhi

28.6667
77.2167

1 comment:

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

    ReplyDelete