In this post, I will show you code for a class that I developed for processing of IP addresses to translate IP address to geo location.
class GeoLocation: def __init__(self, country, city, longitude, latitude): self.country = country self.city = city self.longitude = longitude self.latitude = latitude class Ip2LocationManager: ip2LocationStore = {} def __init__(self): pass @staticmethod def findLocation(ipAddress:str, parseIfNotFound:bool=True) -> GeoLocation: try: result = Ip2LocationManager.ip2LocationStore[ipAddress] except KeyError: country,city,longitude,latitude = Ip2LocationManager.ip2location(ipAddress) result = GeoLocation(country, city,None,None) Ip2LocationManager.ip2LocationStore[ipAddress] = result return result @staticmethod def ip2location(ip) -> Tuple: try: with geoip2.database.Reader('GeoLite2-City.mmdb') as reader: try: response = reader.city(ip) return(response.country.name, response.city.name, response.location.longitude, response.location.latitude) except AddressValueError: print(f'IP address {ip} not found') except FileNotFoundError: print(f'GeoIp2 DB file not found') except ValueError: print(f'Invalid IP address') return ("unknown", "unknown")
Above class has a static method "findLocation" that takes IP address as first parameter. The class has a static variable that keeps dictionary of IP addresses that have already been translated. This way your code will not have to translate IP address for same IP address all the time.
geoLocation = Ip2LocationManager.findLocation(myIpAddress)
This implementation uses MaxMind's GeoIP2 database for IP address translation. You will need to perform following steps before you can use above class.
That's all you will need to convert IP address to location in your python code.
Learn Python: How to convert IP address to location
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2023 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use