Using GeoIP in Python
Geolocation software/services are used to find the actual geographic location of an IP address, the geographic information may be accurate till city/ZIP code level. Maxmind's GeoIP is one such provider of IP address geographic information, they have both free and paid data subscriptions which can be downloaded and used as required, it is also one of most popular amongst developers as it provides APIs in a variety of languages.
The GeoIP databases are provided in two major varieties, the GeoIP Country and GeoIP City, providing upto country level & city level information respectively. These are paid, but Lite versions of both are available for free, which we'll be using in the demo codes to follow.
Various versions of the GeoIP open source C Python library is available at http://www.maxmind.com/download/geoip/api/python, download the latest stable version and unpack it. Pygeoip is a pure Python library, you can check it out at https://github.com/appliedsec/pygeoip, but here we'll be looking at the C Python library from Maxmind.
Issue the following commands from shell as root:
If you have not encountered any errors, the library is installed fine, and we are good to go. In case there was any error, make sure the development code for Python is present in your system.
If you get this error, like I faced, "libGeoIP.so.1: cannot open shared object No such file or directory", then add /usr/local/lib to /etc/ld.so.conf and the following command:
Now, we'll need to download the free version of GeoIP Country & City binary databases from here:
Download and unpack it to a location of your choice, if possible copy it to the following standard location:
We'll implement, a piece of code to try using both City & Country database. Please follow the comments in the code.
GEOIP_MEMORY_CACHE flag uses more memory but provides better performance, it is best suited for batch processing of IP addresses inside a script, the GEOIP_CHECK_CACHE flag if combined with GEOIP_MEMORY_CACHE forces a reload of the database if the database file is modified. The GEOIP_INDEX_CACHE caches the frequently used regions, thereby provides better performance than GEOIP_STANDARD.
|All times are GMT +5.5. The time now is 15:03.|