There is a third-party library called python-geoip, which has a robust interface to answer your IP location query.
You can find more information about this package on the developer's website: http://pythonhosted.org/python-geoip. You can install the package directly from the Python repository.
If you are working with Python 3, you need to install python-geoip-python3 (https://pypi.org/project/python-geoip-python3). This is a fork of python-geoip with Python 3 support. We also need to install the geolite2 module with the pip install python-geoip-geolite2 command:
pip install python-geoip-python3
In the following script, we can see an example of how to use the python-geoip package. You can find the following code in the geoip_lookup.py file:
!/usr/bin/env python3
import socket
from geoip import geolite2
import argparse
import json
# Setup commandline arguments
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname", required=True)
# Parse arguments
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)
print("IP address: {0}".format(ip_address))
match = geolite2.lookup(ip_address)
if match is not None:
print('Country: ',match.country)
print('Continent: ',match.continent)
print('Time zone: ', match.timezone)
print('Location: ', match.location)
This script will show an output similar to the following:
$ python geoip_lookup.py --hostname=amazon.co.uk
IP address: 176.32.98.166
Country: US
Continent: NA
Time zone: None
Location: (38.0, -97.0)