>

A blog about Linux, Debian, Ubuntu, Raspberry Pi and Python.

Stop Being a Fool!
Banks charge huge hidden fees when you send money abroad.
Now you can avoid them completely.


Sunday, 18 May 2014

How To Geolocate an IP Address with Python


Python 2.7.3

First we need a database to match an IP to a location. I am using the Maxmind database, which is available for free.

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz

Next, we install the Pure Python API for Maxmind's GeoIP databases (https://github.com/appliedsec/pygeoip)

sudo pip install pygeoip

Code

import pygeoip
rawdata = pygeoip.GeoIP('/home/user/GeoLiteCity.dat')
def ipquery(ip):
    data = rawdata.record_by_name(ip)
    country = data['country_name']
    city = data['city']
    longi = data['longitude']
    lat = data['latitude']
    print '[x] '+str(city)+',' +str(country)
    print '[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi)
Running the code

How To Geolocate an IP with Python

Facebook Twitter Google Digg Reddit StumbleUpon

1 comments:

  1. Groovy! Except for OSX I had to say:

    cd /usr/local/
    sudo curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
    sudo gunzip /usr/local/GeoLiteCity.dat.gz

    sudo pip install pygeoip

    python2.7
    import pygeoip
    rawdata = pygeoip.GeoIP('/usr/local/GeoLiteCity.dat')

    def ipquery(ip):
    data = rawdata.record_by_name(ip)
    country = data['country_name']
    city = data['city']
    longi = data['longitude']
    lat = data['latitude']
    print '[x] '+str(city)+',' +str(country)
    print '[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi)

    ip='207.38.138.230'
    ipquery(ip)

    [x] New York,United States
    [x] Latitude: 40.7143, Longitude: -74.006

    ReplyDelete