How to Track and Analyze IP Addresses Using Python

Advertisement

Apr 27, 2025 By Alison Perry

When it comes to understanding networks and how devices communicate, IP addresses are right at the heart of it. Every device that connects to the internet has an IP address, whether it's your phone, your laptop, or your smart TV. But what if you wanted to track an IP address using Python? Good news — it’s easier than you might think. And once you get the hang of it, you’ll realize just how much information a simple IP address can reveal.

How Does Python Help in IP Tracking?

Python has a reputation for simplifying complex things. In a matter of a few lines of code, you can retrieve location information, network provider information, and even some information regarding the device itself. All thanks to the genius libraries that do all the heavy work for you. Libraries such as requests, socket, and ipinfo allow you to send requests, get domain names resolved, and retrieve comprehensive IP information with minimal effort.

Let’s break it down:

  • socket: This built-in library helps with DNS lookups and getting local IPs.
  • requests: Makes it easy to connect to web services that provide IP details.
  • ipinfo: A ready-made service that gives you location, city, country, postal code, and more.

Python doesn’t reinvent the wheel here — it simply gives you easy tools to work with.

Simple Ways to Track IP Addresses

If you're just starting out, it's better to work with APIs that give you direct access to IP details. No need to set up complicated servers or scrape through messy data.

Using socket for Basic Tracking

The socket module can quickly get you an IP address from a domain name. Here’s how:

python

CopyEdit

import socket

domain_name = 'google.com'

ip_address = socket.gethostbyname(domain_name)

print(f"The IP address of {domain_name} is {ip_address}")

This gives you the IP address for any domain. It's a small but powerful step, especially when you're dealing with websites.

But what about finding your own IP? You can do that, too:

python

CopyEdit

import socket

hostname = socket.gethostname()

local_ip = socket.gethostbyname(hostname)

print(f"Your local IP address is {local_ip}")

One thing to know: this method only fetches local network IPs or domain-related addresses. It doesn’t show your public IP.

Fetching Public IP Using requests

Your public IP is what websites and online services see when you connect. Python makes it easy to find it:

python

CopyEdit

import requests

public_ip = requests.get('https://api.ipify.org').text

print(f"Your public IP address is: {public_ip}")

What’s happening here is simple. The requests library asks api.ipify.org for your public IP address, and it just returns it — no extra noise.

You can also use different APIs like ipinfo.io or ip-api.com if you want richer information, like location or ISP.

Getting Full Location Details with ipinfo

If you want more than just an IP — like city, region, country, postal code, and organization — then ipinfo is a great choice. Here’s how:

First, install it:

bash

CopyEdit

pip install ipinfo

Then use it like this:

python

CopyEdit

import ipinfo

access_token = 'your_access_token_here'

handler = ipinfo.getHandler(access_token)

ip_address = '8.8.8.8'

details = handler.getDetails(ip_address)

print(details.city)

print(details.region)

print(details.country)

You’ll need an access token, but it’s free for basic use. Once you have it, you can easily pull full reports on any IP.

If you’re curious, try tracking a few different IPs — you’ll notice how much you can learn with just a few lines of code.

Good Practices When Tracking IP Addresses

Now that you know how it’s done, here are a few points that make your scripts better and cleaner.

Respect Privacy

Tracking IP addresses can reveal a lot about someone's physical location and internet habits. Always make sure you have a good reason to collect or look up someone's IP address. If it's for educational purposes or personal experiments, that's fine. But using it in ways that invade privacy isn't just wrong — it could get you in legal trouble.

Use APIs Responsibly

Most public IP services have request limits. Bombarding them with too many requests might get your IP banned. Stick to the fair use guidelines, and cache your results if you can.

For example, if you’re tracking IP addresses in a log file, there’s no need to query the same IP over and over. Save your results locally and only request new data when needed.

Error Handling Matters

Not every request will succeed. Sometimes, the server might be down, your internet might glitch, or the IP address could be invalid. Adding basic error handling saves you from frustration:

python

CopyEdit

try:

public_ip = requests.get('https://api.ipify.org', timeout=5).text

print(f"Your public IP address is: {public_ip}")

except for requests.RequestException as e:

print(f"An error occurred: {e}")

This way, your program won’t just crash. It’ll tell you exactly what went wrong.

Respect Rate Limits

Some APIs are generous, offering thousands of free lookups a month. Others might restrict you to just a few hundred. Always check the documentation and keep your app within limits to avoid unnecessary problems.

Cool Projects You Can Try with IP Tracking

If you’re wondering what you can actually do with this skill, here are a few ideas that can get you started:

Website Visitor Logging: Show visitors their IP address and location when they land on your site.

IP-Based Redirection: Redirect users to different web pages based on their country.

Network Monitoring Tools: Track devices joining your network and get alerts for unknown IPs.

IP Analysis for Cybersecurity: Use IP tracking to spot suspicious behavior on your servers.

Each of these projects can start simple and grow as you learn more.

Wrapping It Up!

Python makes tracking IP addresses almost effortless. Whether you're using built-in libraries like socket, fetching public IPs with requests, or pulling detailed data with ipinfo, it all comes together with just a few lines of code. With a little practice, you’ll be able to build useful tools that not only fetch IP addresses but also make sense of them. Just remember to handle all data responsibly, and you’ll find that working with IP addresses can be both fascinating and extremely useful.

Advertisement

Recommended Updates

Applications

Python Learning Made Easy with These YouTube Channels

By Alison Perry / May 28, 2025

Looking for Python tutorials that don’t waste your time? These 10 YouTube channels break things down clearly, so you can actually understand and start coding with confidence

Applications

Creating Line Plots in Python: A Simple Guide Using Matplotlib

By Alison Perry / Apr 26, 2025

Learn how to create, customize, and master line plots using Matplotlib. From simple plots to advanced techniques, this guide makes it easy for anyone working with data

Applications

4 Quick Ways to Solve AttributeError in Pandas

By Tessa Rodriguez / Apr 24, 2025

Struggling with AttributeError in Pandas? Here are 4 quick and easy fixes to help you spot the problem and get your code back on track

Applications

Why Arc Search’s ‘Call Arc’ Is Changing Everyday Searching

By Alison Perry / Apr 28, 2025

Feeling tired of typing out searches? Discover how Arc Search’s ‘Call Arc’ lets you speak your questions and get instant, clear answers without the hassle

Applications

Essential pip Commands for Installing and Updating Packages

By Tessa Rodriguez / Apr 27, 2025

Need to install, update, or remove Python libraries? Learn the pip commands that keep your projects clean, fast, and hassle-free

Technologies

How Python Makes Text Mining Easy for Beginners

By Tessa Rodriguez / Apr 27, 2025

Curious how companies dig insights out of words? Learn how to start text mining with Python and find hidden patterns without feeling overwhelmed

Technologies

Making Data Simpler with Python’s Powerful filter() Function

By Alison Perry / Apr 27, 2025

Looking for a better way to sift through data? Learn how Python’s filter() function helps you clean lists, dictionaries, and objects without extra loops

Applications

7 Must-Know Python Libraries for Effective Data Visualization

By Alison Perry / Apr 28, 2025

Which Python libraries make data visualization easier without overcomplicating things? This list breaks down 7 solid options that help you create clean, useful visuals with less hassle

Applications

7 University-Level Machine Learning Courses You Can Take for Free

By Tessa Rodriguez / Apr 28, 2025

Looking to learn machine learning without spending a dime? These 7 free university courses break things down simply and help you build real skills from scratch

Technologies

Finding and Checking Armstrong Numbers with Easy Python Code

By Alison Perry / Apr 27, 2025

Ever spotted numbers that seem special? Learn how Armstrong numbers work and see how easy it is to find them using simple Python code

Applications

How to Track and Analyze IP Addresses Using Python

By Alison Perry / Apr 27, 2025

Learn how to track, fetch, and analyze IP addresses using Python. Find public IPs, get location details, and explore simple project ideas with socket, requests, and ipinfo libraries

Technologies

Mastering ROW_NUMBER() in SQL: Numbering, Pagination, and Cleaner Queries Made Simple

By Alison Perry / Apr 26, 2025

Learn how ROW_NUMBER() in SQL can help you organize, paginate, and clean your data easily. Master ranking rows with practical examples and simple tricks