Last modified: Jun 09, 2025 By Alexander Williams
Install pygeoip in Python - Quick Guide
pygeoip is a Python library for geo-location tasks. It helps map IP addresses to geographic locations. This guide explains how to install and use it.
Table Of Contents
Prerequisites
Before installing pygeoip, ensure you have Python 3.6+. Check your version with:
import sys
print(sys.version)
You also need pip. Update pip to avoid issues:
python -m pip install --upgrade pip
Install pygeoip
Use pip to install pygeoip. Run this command:
pip install pygeoip
For a specific version, specify it:
pip install pygeoip==0.3.2
Verify Installation
Check if pygeoip installed correctly:
import pygeoip
print(pygeoip.__version__)
This should print the installed version.
Download GeoIP Database
pygeoip needs a GeoIP database. Download it from MaxMind:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
Place the file in your project directory.
Basic Usage
Here's how to use pygeoip:
import pygeoip
# Load the GeoIP database
gi = pygeoip.GeoIP('GeoLiteCity.dat')
# Get location data for an IP
ip = '8.8.8.8'
data = gi.record_by_addr(ip)
print(data)
This code prints location details for Google's DNS IP.
Example Output
The output looks like this:
{
"city": "Mountain View",
"region_name": "California",
"country_name": "United States",
"longitude": -122.0838,
"latitude": 37.3860
}
Common Methods
pygeoip offers useful methods:
record_by_addr
- Gets data by IP addressrecord_by_name
- Gets data by hostnamecountry_code_by_addr
- Gets country code
Troubleshooting
If you get errors, try these fixes:
Database not found: Ensure the .dat file path is correct.
ImportError: Reinstall pygeoip if import fails.
For similar installations, see How to Install dnspython in Python.
Alternatives
Consider these libraries for similar tasks:
- geoip2 - Newer MaxMind library
- ip2geotools - Alternative geo-location tool
For security tasks, check Install PyCryptodome in Python.
Conclusion
pygeoip is simple for IP geo-location tasks. Install it with pip, get a GeoIP database, and start mapping IPs.
Remember to handle location data responsibly and comply with privacy laws.