Sling Academy
Home/Python/Python: 3 Ways to Retrieve City/Country from IP Address

Python: 3 Ways to Retrieve City/Country from IP Address

Last updated: February 19, 2024

Overview

Discovering the geographic location of a user based on their IP address is a common need in many web and network applications. This guide walks through several methods to achieve this in Python, detailing their implementation, use cases, and considerations.

Solution 1: Using GeoIP2 Database

The GeoIP2 database by MaxMind is a popular choice for offline IP geolocation. It offers high accuracy and is updated frequently. You can use the GeoIP2 or GeoLite2 databases, with the latter being a free version with slightly reduced accuracy.

  1. Download the GeoLite2 City database from the MaxMind website.
  2. Install the geoip2 library with pip install geoip2.
  3. Use the database to query an IP address for its location.

Example:

import geoip2.database
reader = geoip2.database.Reader('/path/to/GeoLite2-City.mmdb')
response = reader.city('128.101.101.101')
print(response.country.name)
print(response.city.name)
reader.close()

Notes: This method requires downloading and keeping the database updated manually. Its performance is reliant on the local system’s resources, making it a good option for offline applications or where data privacy is a concern.

Solution 2: Using ipinfo.io API

For online solutions, ipinfo.io provides a convenient API that offers various details about an IP address, including location information. It requires an internet connection and has a free tier with limited requests per month.

  1. Sign up at ipinfo.io and get your access token.
  2. Install requests library with pip install requests.
  3. Make a GET request to the ipinfo.io API with the desired IP address.

Exanple:

import requests
access_token = 'your_access_token'
response = requests.get('https://ipinfo.io/128.101.101.101/json?token=' + access_token)
data = response.json()
print(data['country'])
print(data['city'])

Notes: The ipinfo.io API solution is great for applications that require real-time data without the need to maintain a local database. However, relying on external APIs introduces latency and limits based on the plan you’re subscribed to.

Solution 3: Using Python GeoIP Library

The GeoIP library is another way to perform IP-based geolocation in Python. Although not as feature-rich as GeoIP2, it provides basic functionality for resolving IP addresses to country/city with minimal setup.

  1. Install the Python GeoIP library with pip install python-geoip.
  2. Use the library to query an IP address.

Example:

from geoip import geolite2
match = geolite2.lookup('128.101.101.101')
if match is not None:
print(match.country)
print(match.timezone)

Notes: This solution is simple and lightweight, suitable for applications that require basic geolocation features without the complexity of configuring and maintaining a database.

Conclusion

Choosing the right method for geolocating IP addresses in Python depends on your application’s requirements, including the need for accuracy, real-time data, and resource availability. Offline database solutions offer privacy and control but require manual updates, whereas online APIs provide real-time data with minimal setup at the expense of introducing external dependencies and potential costs.

Next Article: Python: How to programmatically run Git commands and parse the output

Previous Article: Python: How to extract only tables from raw HTML

Series: Python – Fun Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs