Learn Python: How to convert IP address to location

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.

  • Download "GeoLite2-City.mmdb" database file from https://www.maxmind.com/en/geoip2-databases
  • You can copy the file anywhere you wish to. If you keep this file in folder other than location of your python file, then you will need to specify correct path in the code initiating geoip2 library: geoip2.database.Reader('GeoLite2-City.mmdb').
  • Install geoip2 python on your machine using pip install geoip2.

That's all you will need to convert IP address to location in your python code.

Search

Social

Weather

17.0 °C / 62.5 °F

weather conditions Mist

Monthly Posts

Blog Tags