Advertisement
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.
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:
Python doesn’t reinvent the wheel here — it simply gives you easy tools to work with.
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.
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.
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.
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.
Now that you know how it’s done, here are a few points that make your scripts better and cleaner.
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.
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.
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.
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.
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.
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
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
By Tessa Rodriguez / Apr 26, 2025
Discover how Alibaba Cloud's Qwen2 is changing the game in open-source AI. Learn what makes it unique, how it helps developers and businesses, and why it’s worth exploring
By Alison Perry / Apr 27, 2025
Looking for a faster way to update every item in a list? Learn how Python’s map() function helps you write cleaner, quicker, and more readable code
By Tessa Rodriguez / Apr 27, 2025
Learn different ways to handle exponents in Python using ** operator, built-in pow(), and math.pow(). Find out which method works best for your project and avoid common mistakes
By Alison Perry / Apr 27, 2025
Wondering how apps create art, music, or text automatically? See how generative models learn patterns and build new content from what they know
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
By Tessa Rodriguez / Apr 27, 2025
Explore how Kolmogorov-Arnold Networks (KANs) offer a smarter, more flexible way to model complex functions, and how they differ from traditional neural networks
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
By Tessa Rodriguez / Apr 27, 2025
Ever noticed numbers that read the same backward? Learn how to check, create, and play with palindrome numbers using simple Python code
By Tessa Rodriguez / Apr 28, 2025
Ever wondered how your favorite apps know exactly what you need? Discover how algorithms solve problems, guide decisions, and power modern technology
By Alison Perry / Apr 27, 2025
Frustrated with slow and clumsy database searches? Learn how the SQL CONTAINS function finds the exact words, phrases, and patterns you need, faster and smarter
By Tessa Rodriguez / Apr 26, 2025
Learn how to use HLOOKUP in Excel with simple examples. Find out when to use it, how to avoid common mistakes, and tips to make your formulas smarter and faster