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

Updated: February 19, 2024 By: Guest Contributor Post a comment


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.


import geoip2.database
reader = geoip2.database.Reader('/path/to/GeoLite2-City.mmdb')
response ='')

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 API

For online solutions, 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 and get your access token.
  2. Install requests library with pip install requests.
  3. Make a GET request to the API with the desired IP address.


import requests
access_token = 'your_access_token'
response = requests.get('' + access_token)
data = response.json()

Notes: The 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.


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

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


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.