IP address geolocation has become an increasingly useful capability in today’s connected world. This guide will walk through how to track an IP address’s geographic location using Python. We’ll provide code examples that leverage Python libraries to fetch location data like city, region and coordinates for a given IP address. Mapping IPs to real-world locations enables various applications, from security monitoring to content localization. Follow along as we explore this functionality using Python.
To track an IP address, we will use the following Python libraries:
Before we start, make sure you have Python installed on your machine. You can install the required libraries using pip:
Code:
!pip install requests ip2geotools geopy
Here is a step-by-step guide to tracking IP addresses using Python:
First, we need to get the IP address we want to track. We can use the `requests` library to fetch our public IP address from an external service.
Code:
import requests
def get_public_ip():
response = requests.get('https://api64.ipify.org?format=json')
ip_address = response.json()['ip']
return ip_address
print("Your public IP address is:", get_public_ip())
Once we have the IP address, we can use the `ip2geotools` library to fetch geolocation data. This library supports both IPv4 and IPv6 addresses and provides detailed location information.
Code:
from ip2geotools.databases.noncommercial import DbIpCity
def get_location(ip):
response = DbIpCity.get(ip, api_key='free')
location_data = {
"IP Address": response.ip_address,
"City": response.city,
"Region": response.region,
"Country": response.country,
"Latitude": response.latitude,
"Longitude": response.longitude
}
return location_data
ip_address = get_public_ip()
location = get_location(ip_address)
print("Location data:", location)
Using the `geopy` library, we can calculate the distance between two sets of coordinates. This can be useful for applications like measuring the distance between the user and a server.
Code:
from geopy.distance import distance
def calculate_distance(coord1, coord2):
return distance(coord1, coord2).km
# Example coordinates (Latitude, Longitude)
coord1 = (location['Latitude'], location['Longitude'])
coord2 = (37.7749, -122.4194) # San Francisco, CA
print(f"Distance between {coord1} and {coord2}: {calculate_distance(coord1, coord2)} km")
Also Read: Top 50+ Geospatial Python Libraries
In addition to IP addresses, you might also want to get the IP address of a URL. This can be done using the `socket` library.
Code:
import socket
def get_ip_from_url(url):
ip_address = socket.gethostbyname(url)
return ip_address
url = 'www.google.com'
ip_from_url = get_ip_from_url(url)
print(f"IP address of {url} is {ip_from_url}")
print("Location data:", get_location(ip_from_url))
Let us now look at some use cases.
You can use geolocation data to block or allow access from specific countries. Here’s an example function that checks if an IP address is from a blocked country:
Code:
blocked_countries = ["China", "Russia", "North Korea"]
def is_country_blocked(ip):
location = get_location(ip)
return location['Country'] in blocked_countries
ip_to_check = '8.8.8.8' # Example IP
if is_country_blocked(ip_to_check):
print(f"Access from {ip_to_check} is blocked.")
else:
print(f"Access from {ip_to_check} is allowed.")
You can also calculate the distance between two IP addresses:
Code:
ip1 = '8.8.8.8'
ip2 = '1.1.1.1'
location1 = get_location(ip1)
location2 = get_location(ip2)
coord1 = (location1['Latitude'], location1['Longitude'])
coord2 = (location2['Latitude'], location2['Longitude'])
print(f"Distance between {ip1} and {ip2}: {calculate_distance(coord1, coord2)} km")
Tracking the location of an IP address using Python is a powerful tool for various purposes. Following this guide, you can fetch geolocation data, calculate distances, and implement location-based restrictions. This comprehensive approach ensures you have all the tools necessary to get started with IP tracking in Python. Remember to respect privacy and comply with legal regulations when using IP tracking in your applications. To learn more about Python, enroll in our free Python course today!