Last modified: Jun 01, 2025 By Alexander Williams
Install PyGeoIP in Python Easily
PyGeoIP is a Python library for geolocation tasks. It helps find location details from IP addresses. This guide covers installation and basic usage.
What Is PyGeoIP?
PyGeoIP provides geolocation data from IP addresses. It uses GeoIP databases to fetch country, city, and other details. It's useful for analytics and security.
PyGeoIP is lightweight and easy to integrate. It supports both IPv4 and IPv6 addresses. You can also use it with PyCryptodome for secure applications.
Install PyGeoIP in Python
PyGeoIP can be installed using pip. Ensure you have Python and pip installed. Run the following command in your terminal.
pip install pygeoip
If you face issues, try upgrading pip first. This ensures compatibility with the latest packages.
pip install --upgrade pip
Download GeoIP Database
PyGeoIP needs a GeoIP database file. Download it from MaxMind or other sources. The free version works for basic tasks.
Place the database file in your project folder. Common names are GeoIP.dat
or GeoLiteCity.dat
. You can also use PyTables for big data handling.
Basic PyGeoIP Usage
Here’s a simple example to get started. The code fetches country details from an IP.
import pygeoip
# Load the GeoIP database
geoip = pygeoip.GeoIP('GeoIP.dat')
# Get country by IP
country = geoip.country_name_by_addr('8.8.8.8')
print(country)
United States
The country_name_by_addr
method returns the country name. Replace the IP with any valid address.
Advanced PyGeoIP Features
PyGeoIP can fetch city, region, and timezone details. Use the GeoLiteCity.dat
database for more data.
import pygeoip
# Load the city database
geoip = pygeoip.GeoIP('GeoLiteCity.dat')
# Get city details by IP
record = geoip.record_by_addr('8.8.8.8')
print(record)
{'city': 'Mountain View', 'region_name': 'California', 'country_name': 'United States', 'time_zone': 'America/Los_Angeles'}
The record_by_addr
method returns a dictionary. It includes city, region, and timezone details.
Error Handling
Always handle errors when using PyGeoIP. Invalid IPs or missing databases can cause issues.
import pygeoip
try:
geoip = pygeoip.GeoIP('GeoIP.dat')
country = geoip.country_name_by_addr('invalid_ip')
print(country)
except Exception as e:
print(f"Error: {e}")
Error: Invalid IP address
This ensures your application doesn’t crash. Use similar checks for database loading.
Conclusion
PyGeoIP is a powerful tool for geolocation tasks. It’s easy to install and use with Python. Follow this guide to integrate it into your projects.
For more Python libraries, check How to Install dnspython in Python Easily or Install PyCryptodome in Python Easily.