GeoLocation in Python

When performing a security analysis, it is often desirable to know the country and sometimes even the city from where traffic is originating from.  There are a variety of websites, like,  that allow you to enter in an IP address and will report back the city and country as well as possibly the longitude and latitude based on data from an Internet Registry’s Whois database.

However, many of these web services require a subscription for bulk lookups over a certain volume.  For commercial applications, a geolocation subscription will probably be money well spent.  However, sometimes you have a list of multiple IP addresses and want to perform the lookup yourself. has published lists of files with IP GeoLocation Data under the Creative Commons Attribution-ShareAlike 3.0 Unported License. They update these files on the first Tuesday of each month.

The following two Python programs demonstrate a simple lookup.  The first program ( performs the lookup on the file that contains the country associated with the IP address block, while the second program ( provides the detail down to the city level.

These programs only work for IPv4 addresses.  Also, it assumes the the IPListFile has a header and is in the format of:


Tagged , , , , . Bookmark the permalink.
  • The postings and views on this site are my own and do not necessarily reflect the positions, strategies, or opinions of any current or previous employer. © Kenneth G. Hartman 2010-2018