IP Address Geolocation With Python

This script was done in Python 3.4.3 for an exercise in OPS635.

Attempting to find the geographic location of an IP address can be quite frustrating with python on Linux. I had several issues attempting to get a library and database that were compatible with each other. Eventually I realized that the version of the database both openSUSE and Fedora ship were not compatible with the version of pygeoip that pip installs. To work around this, I had to manually download the GeoIP database from here and save it somewhere on the filesystem. Then I just told python the path to the database and everything seemed to work fine from there. Here is the script, feel free to use it as you wish:

import pygeoip

def ipLocator(ip):
    GeoIPDatabase = '/home/user/GeoLiteCity.dat'
    ipData = pygeoip.GeoIP(GeoIPDatabase)
    record = ipData.record_by_name(ip)
    print("The geolocation for IP Address %s is:" % ip)
    print("Accurate Location: %s, %s, %s" % (record['city'], record['region_code'], record['country_name']))
    print("General Location: %s" % (record['metro_code']))
This entry was posted in Linux, Monitoring, Python and tagged , , , , . Bookmark the permalink.

3 Responses to IP Address Geolocation With Python

  1. Pingback: Links 24/1/2016: Linux 4.5 RC1, Debian 8.3 Released | Techrights

  2. Bartek says:

    What is the point in downloading the constant library while public IP addresses
    changing in time?

    • Uzair Shamim says:

      Are you referring to the GeoIP database? As I mentioned the script was just a quick task done for a class project, it was not meant to be persistent for long periods of time. You are correct that over time it would become inaccurate but the versions supplied by the distributions I tried simply did not work. The best bet would probably be to write some scheduled job to occasionally update the DB.

      I hope that answered your question.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s