Getting geolocation by IP using ip2geotools.
Recently, I discovered an intriguing package, ip2geotools
which provides the ability to obtain geolocation by IP from various databases.
An example of code to get information by IP using the DbIpCity
class, which represents a non-commercial database, looks as follows:
from ip2geotools.databases.noncommercial import DbIpCity
def get_ip_geolocation(ip_address):
try:
response = DbIpCity.get(ip_address, api_key='free')
city = response.city
region = response.region
country = response.country
latitude = response.latitude
longitude = response.longitude
print(f"Location information for the IP {ip_address}:")
print(f"City: {city}")
print(f"Region: {region}")
print(f"Country: {country}")
print(f"Latitude: {latitude}")
print(f"Longitude: {longitude}")
except Exception as e:
print(f"Error when retrieving information by IP {ip_address}: {e}")
ip_address_to_check = '8.8.8.8'
get_ip_geolocation(ip_address_to_check)
This code uses the get
method from the DbIpCity
class to retrieve location information for a given IP address. Keep in mind that some databases may require an API key for use.
Page of .
Leave a comment
You must be logged in to leave a comment.
Log in or
sign up to join the discussion.
Comments (0)