Wednesday, February 6, 2008

Geocoding IP addresses with GeoIP City (GeoLite)

First install both the GeoIP C Library and the Python bindings.

Download the GeoLite/GeoIP City binary data file, and install the .dat file::
$ mv GeoLiteCity.dat /usr/local/share/GeoIP/GeoIPCity.dat
In a Python shell:
>>> import GeoIP
>>> geoip_lib = '/usr/local/share/GeoIP/GeoIPCity.dat'
>>> gi = GeoIP.open(geoip_lib, GeoIP.GEOIP_MEMORY_CACHE)

>>> print gi.record_by_name("google.com")
{'city': 'Mountain View', 'region': 'CA', 'area_code': 650, 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}
>>> print gi.record_by_addr("64.233.167.99")
{'city': 'Mountain View', 'region': 'CA', 'area_code': 650, 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}
Some quick tests showed that GeoLite City correctly geocoded 4 out of 6 (somewhat random) samples I threw at it, compared to the GeoIP web service, which presumably uses their full GeoIP database. For example, it wasn't able to geocode Microsoft.com (207.46.197.32) and matched my work IP address to LA when it should be in the Bay Area.

No comments: