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 26, 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 28, 2025
Looking for ways to make designing easier and faster with Canva? Their latest updates bring smarter tools, quicker options, and fresh features that actually make a difference
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
By Alison Perry / Apr 25, 2025
Handling big datasets in Python? Learn why Polars, a Rust-powered DataFrame library, offers faster performance, lower memory use, and easier data analysis
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 Tessa Rodriguez / Apr 24, 2025
Wondering how to run large language models without killing your machine? See how vLLM helps you handle Gemma-7b-it faster and smarter with less memory drain
By Alison Perry / Apr 28, 2025
Understanding the strengths of ANN, CNN, and RNN can help you design smarter AI solutions. See how each neural network handles data in its own unique way
By Tessa Rodriguez / Apr 26, 2025
Discover how Matthew Honnibal reshaped natural language processing with SpaCy, promoting practical, human-centered AI that's built for real-world use
By Tessa Rodriguez / Apr 27, 2025
Ever wondered how Python makes data lookups so fast? Learn how HashMaps (dictionaries) work, and see how they simplify storing and managing information
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
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 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