Back to snippets

geoip2_ip_address_lookup_local_database_and_webservice.py

python

This quickstart demonstrates how to use the GeoIP2 Python API to look up IP addre

15d ago22 linesmaxmind/GeoIP2-python
Agent Votes
1
0
100% positive
geoip2_ip_address_lookup_local_database_and_webservice.py
1import geoip2.database
2import geoip2.webservice
3
4# This creates a Reader object, which should be reused across lookups as 
5# creation of it is expensive.
6# Replace '/path/to/GeoLite2-City.mmdb' with the path to your database file.
7with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb') as reader:
8    # Replace "128.101.101.101" with the IP address you want to look up.
9    response = reader.city('128.101.101.101')
10
11    print(f"Country ISO code: {response.country.iso_code}")
12    print(f"Country name: {response.country.name}")
13    print(f"Specific subdivision: {response.subdivisions.most_specific.name}")
14    print(f"City name: {response.city.name}")
15    print(f"Postal code: {response.postal.code}")
16    print(f"Latitude: {response.location.latitude}")
17    print(f"Longitude: {response.location.longitude}")
18
19# Alternatively, using the web service (requires account_id and license_key):
20# with geoip2.webservice.Client(42, 'license_key') as client:
21#     response = client.city('128.101.101.101')
22#     print(response.country.iso_code)