Created
September 16, 2022 16:16
-
-
Save cosimo/e1568a56d5f9b78705d9148de9db81b1 to your computer and use it in GitHub Desktop.
Simple GeoIP2 IP latitude, longitude lookup in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Looks up an IP address using GeoLite2 City Database | |
""" | |
from functools import lru_cache | |
import geoip2.database | |
import geoip2.errors | |
import sys | |
geoip_db_path = "/usr/local/share/GeoIP/GeoLite2-City.mmdb" | |
geoip_reader = geoip2.database.Reader(geoip_db_path) | |
@lru_cache(maxsize=10000) | |
def geolookup_ip(ip): | |
try: | |
geoip_response = geoip_reader.city(ip) | |
except geoip2.errors.AddressNotFoundError: | |
return (0, 0) | |
except: | |
return (0, 0) | |
lat = geoip_response.location.latitude | |
lon = geoip_response.location.longitude | |
return (lat, lon) | |
ip = sys.argv[1] | |
print(geolookup_ip(ip)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment