How to Track IP Address Using Python?

NISHANT TIWARI Last Updated : 04 Jun, 2024
3 min read

Introduction

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.

Tools and Libraries

To track an IP address, we will use the following Python libraries:

  • ‘requests’: To make HTTP requests.
  • ‘ip2geotools’: To get geolocation data.
  • ‘geopy’: To calculate distances between coordinates.

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

Step-by-Step Guide to Track IP Address Using Python

Here is a step-by-step guide to tracking IP addresses using Python:

Getting the IP Address

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())

Fetching Geolocation Data

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)

Distance Calculation

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

Handling URLs

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))

Common Use Cases

Let us now look at some use cases.

Blocking IP Addresses Based on Location

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.")

Calculating Distance Between Two IP Addresses

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")

Conclusion

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!

Seasoned AI enthusiast with a deep passion for the ever-evolving world of artificial intelligence. With a sharp eye for detail and a knack for translating complex concepts into accessible language, we are at the forefront of AI updates for you. Having covered AI breakthroughs, new LLM model launches, and expert opinions, we deliver insightful and engaging content that keeps readers informed and intrigued. With a finger on the pulse of AI research and innovation, we bring a fresh perspective to the dynamic field, allowing readers to stay up-to-date on the latest developments.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details