Skip to content

Instantly share code, notes, and snippets.

@cosimo
Created September 16, 2022 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosimo/e1568a56d5f9b78705d9148de9db81b1 to your computer and use it in GitHub Desktop.
Save cosimo/e1568a56d5f9b78705d9148de9db81b1 to your computer and use it in GitHub Desktop.
Simple GeoIP2 IP latitude, longitude lookup in Python 3
#!/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