Signup/Sign In

Using pyGeoIP Module

You must have stumbled across various websites which display your location, city, area etc. as soon you visit their webpages. Ever wondered how? These websites use some sort of paid databases which help them to correlate physical location with IP addressess with great accuracy. In this lesson we will use a free database which will roughly do the same thing. The database is named GeoLiteCity.dat.

To map or corelate IP addresses with physical location we will be using python's pyGeoIP module.

To install the pyGeoIP module, use pip command:

pip install pygeoip

pygeoip provides for multiple different type of lookups, like:

  1. Country Lookup
    >>> import pygeoip
    >>> gi = pygeoip.GeoIP('GeoLiteCity.dat')
    >>> gi.country_name_by_addr('')


  2. Region Lookup
    >>>import pygeoip
    >>> gi = pygeoip.GeoIP('GeoLiteCity.dat')
    >>> gi.region_by_addr('')

    {'region_code': u'07', 'country_code': 'IN'}

    >>>import pygeoip
    >>> gi = pygeoip.GeoIP('GeoLiteCity.dat')
    >>> gi.region_by_name('')

    {'region_code': u'CA', 'country_code': 'US'}

  3. City Lookup
    >>>import pygeoip
    >>>  gi = pygeoip.GeoIP(‘GeoLiteCity.dat’)
    >>>  gi.record_by_addr(‘’)

    { 'city': u'New Delhi', 'region_code': u'07', 'area_code': 0, 'time_zone': 'Asia/Calcutta', 'dma_code': 0, 'metro_code': None, 'country_code3': 'IND', 'latitude': 28.599999999999994, 'postal_code': None, 'longitude': 77.19999999999999, 'country_code': 'IN', 'country_name': 'India', 'continent': 'AS' }

  4. Organization Lookup
    >>>import pygeoip
    >>> gi = pygeoip.GeoIP('GeoLiteCity.dat')
    >>> gi.org_by_name('')

    'Dell Computer Corporation'

Program for using pygeoip module

#!usr/bin/env python

import pygeoip

gi = pygeoip.GeoIP('GeoLiteCity.dat')
def printRecord(ip):
	rec = gi.record_by_name(ip)
	city = rec['city']
	country = rec['country_name']
	longitude = rec['longitude']
	lat = rec['latitude']
	print '[+] Address: '  + ip + ' Geo-located '
	print '[+] ' +str(city)+ ', '+str(country)
	print '[+] Latitude: ' +str(lat)+ ', Longitude: '+ str(longitude)

ip = # Enter an IP(in single quotes)

Now in this program, we have hardcoded the IP address, but you can convert this program to start taking command line inputs at runtime. Remember? We learnt how to do that using argparse and optparse in this tutorial