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:

[code lang=”python”]
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’]))
[/code]