How to Track the Location of an IP Address using Python

Learn how to geolocate an IP Address or a Domain Name using the python library named Ip2geotools.



How to Track the Location of an IP Address using Python
Image by Author

 

We will use a python library named ip2geotools that allows you to determine the physical location of an IP address. This can determine an IP address's country, region, city, latitude, and longitude.

It supports IPv4 and IPv6 addresses and can handle single IP addresses and lists of IP addresses. But it is important to note that the library is not accurate 100% of the time, and the accuracy of the results will depend on the data source used and the quality of the data. However, it is widely used, and the community is active, so the library is updated regularly.

 

Getting Location from IP Address

 

In this section, we will discuss the python code to extract the location from an IP address or a URL.

 

1. Importing necessary Libraries

 

$ pip install ip2geotools

 

import socket
import requests
from ip2geotools.databases.noncommercial import DbIpCity
from geopy.distance import distance

 

The below function is used to print the details of the IP address line City, Country, Coordinates, etc.

def printDetails(ip):
    res = DbIpCity.get(ip, api_key="free")
    print(f"IP Address: {res.ip_address}")
    print(f"Location: {res.city}, {res.region}, {res.country}")
    print(f"Coordinates: (Lat: {res.latitude}, Lng: {res.longitude})")

 

2. Getting the Location from an IP Address

 

ip_add = input("Enter IP: ")  # 198.35.26.96
printDetails(ip_add)

 

Output:

IP Address: 198.35.26.96
Location: San Jose, California, US
Coordinates: (Lat: 37.3361663, Lng: -121.890591)

 

3. Getting Location from a URL

 

url = input("Enter URL: ")  # www.youtube.com
ip_add = socket.gethostbyname(url)
printDetails(ip_add)

 

Output:

Enter the URL: www.youtube.com
IP Address: 173.194.214.91
Location: Mountain View, California, US
Coordinates: (Lat: 37.3893889, Lng: -122.0832101)

 

Some Common Use Cases

 

Here we discuss some of its use cases like blocking the IP addresses of some specific countries or two calculate the distance between the two IP addresses, etc.

 

1. Block certain IP Addresses Based on their Location

 

The below code look up the location of an IP address and then checks if the country of that location is in the list of blocked countries or not.

def is_country_blocked(ip_address):
    blocked_countries = ["China", "Canada", "India"]
    location = DbIpCity.get(ip_address)
    if location.country in blocked_countries:
        return True
    else:
        return False


ip_add = input("Enter IP: ")  # 198.35.26.96
if is_country_blocked(ip_add) is True:
    print(f"IP Address: {ip_add} is blocked")
else:
    print(f"IP Address: {ip_add} is allowed")

 

Output:

Enter the IP Address: 198.35.26.96
IP Address: 198.35.26.96 is allowed

 

You can also modify that code to allow IP addresses from a specific country.

 

2. Calculate the Distance between two IP Addresses

 

The below code will calculate the distance (in km) between the two IP address locations.

def calculate_distance(ip1, ip2):
    res1 = DbIpCity.get(ip1)
    res2 = DbIpCity.get(ip2)
    lat1, lon1 = res1.latitude, res1.longitude
    lat2, lon2 = res2.latitude, res2.longitude
    return distance((lat1, lon1), (lat2, lon2)).km


# Input two IP addresses
ip_add_1 = input("1st IP: ")  # 198.35.26.96
ip_add_2 = input("2nd IP: ")  # 220.158.144.59
dist = calculate_distance(ip_add_1, ip_add_2)
print(f"Distance between them is {str(dist)}km")

 

Output:

Enter 1st IP Address: 198.35.26.96
Enter 2nd IP Address: 220.158.144.59
Distance between them is 12790.62320788363km

 

3. Calculate the Distance between your Current Location and the Server

 

The below code will calculate the distance (in km) between your current location and the given IP address location.

def get_distance_from_location(ip, lat, lon):
    res = DbIpCity.get(ip)
    ip_lat, ip_lon = res.latitude, res.longitude
    return distance((ip_lat, ip_lon), (lat, lon)).km

server_ip = input("Server's IP: ")
lat = float(input("Your Latitude: "))
lng = float(input("Your Longitude: "))

dist = get_distance_from_location(server_ip, lat, lng)
print(f"Distance between the server and your location is {str(dist)}km")

 

Output:

Enter your server's IP Address: 208.80.152.201
Enter your current location (Latitude): 26.4710
Enter your current location (Longitude): 73.1134
Distance between the server and your location is 12183.275099919923km

 

Conclusion

 

There are several benefits of tracking the location of an IP address, like businesses can deliver targeted advertising to users based on their location. This can lead to more effective marketing campaigns, higher conversion rates, and personalizing the user’s experience.

Also, it can be beneficial in fraud detection, like blocking IP addresses from some specific countries, also validate IP addresses to ensure that they are properly formatted.

In conclusion, I hope you have enjoyed this article and found it informative. You can find the collaboratory file of the complete code. If you have any suggestions or feedback, please reach out to me via LinkedIn.

Have a nice day????.

 
 
Aryan Garg is a B.Tech. Electrical Engineering student, currently in the final year of his undergrad. His interest lies in the field of Web Development and Machine Learning. He have pursued this interest and am eager to work more in these directions.