Introduction
Python is the leading language for automation, web scraping, backend API development, and data engineering. In many scripts and applications, identifying the public IP address of the machine running the code is critical.
For instance, if you are running a distributed web scraper across multiple cloud proxies, you need to verify which proxy IP is currently active. Similarly, if you are building an automated server installer, you might need to register the host's public IP in a remote DNS configuration or a database.
Because Python runs on local servers, desktops, or cloud containers, it cannot query the public internet to determine its own public IP directly from its local network interfaces (which typically report local private IPs like 192.168.1.15 or 10.0.0.4). Instead, Python must make an external HTTP request to resolve its public-facing gateway IP.
In this guide, we will walk through the most popular, efficient, and robust methods for getting your public IP address in Python.
Method 1: Using the requests Library (Recommended)
The requests library is the gold standard for HTTP queries in Python due to its simple, intuitive syntax. If you don't mind installing an external dependency, this is the cleanest solution.
First, install the library if you haven't already:
pip install requests
Here is how to fetch and parse your public IP in Python using requests with a JSON endpoint:
import requests
def fetch_public_ip():
url = "https://tracethatip.com/json"
try:
# Send HTTP GET request with a short timeout limit
response = requests.get(url, timeout=5)
# Raise an exception for 4xx or 5xx HTTP status codes
response.raise_for_status()
# Parse the JSON response
data = response.json()
print(f"My Public IP Address is: {data['ip']}")
return data['ip']
except requests.exceptions.Timeout:
print("Error: The request timed out.")
except requests.exceptions.RequestException as e:
print(f"Error querying IP API: {e}")
return None
if __name__ == "__main__":
fetch_public_ip()
Method 2: Using standard urllib (No Dependencies)
If you are writing scripts that must run in environment-restricted environments (like cloud functions, AWS Lambda, or systems where you cannot install external pip packages), Python's standard library urllib is the perfect dependency-free solution.
import urllib.request
import json
def fetch_public_ip_stdlib():
url = "https://tracethatip.com/json"
req = urllib.request.Request(
url,
headers={"User-Agent": "Python-StdLib-IP-Fetcher"}
)
try:
# Fetch the response body
with urllib.request.urlopen(req, timeout=5) as response:
html = response.read().decode("utf-8")
data = json.loads(html)
print(f"My Public IP (StdLib) is: {data['ip']}")
return data['ip']
except urllib.error.URLError as e:
print(f"Failed to query URL: {e}")
except json.JSONDecodeError:
print("Failed to parse JSON response.")
return None
if __name__ == "__main__":
fetch_public_ip_stdlib()
Method 3: Getting Plain Text (Fast & Light)
For script tasks that run repeatedly (where JSON parsing overhead is undesirable), you can query our raw plain-text endpoint. This returns just the clean IP string with no formatting.
import requests
def get_raw_ip():
try:
# Querying the raw plain text endpoint
ip = requests.get("https://tracethatip.com/raw", timeout=3).text.strip()
print(f"Raw IP: {ip}")
return ip
except requests.RequestException as e:
print(f"Error: {e}")
return None
if __name__ == "__main__":
get_raw_ip()
Use Cases for Python IP Lookups
Integrating IP detection inside Python scripts unlocks multiple automated workflows:
1. Web Scraping & Proxy Rotation Verification
When scraping websites, servers often block IPs that make too many requests. To avoid blocks, scrapers rotate through IP proxies. You can write a wrapper around your scraper to check the active IP before executing key tasks:
# Pseudo-code verification
active_ip = get_raw_ip()
if active_ip == "Your-Home-IP":
raise Exception("Security Risk: Proxy rotation failed! Aborting scraping.")
2. Dynamic DNS Updates
If you host a local server at home but your ISP assigns you a dynamic IP that changes periodically, you can write a cron-job script in Python that:
- Detects your public IP.
- Compares it with your last saved IP.
- If it changed, calls your DNS provider's API (like Cloudflare or GoDaddy) to update your domain records.
Best Practices for Python Network Requests
- Set Timeout Limits: Always specify a
timeoutargument in your network queries. If network routes drop, without a timeout, your Python script can hang indefinitely, locking resources. - Cache IP Results: Avoid querying the IP API on every single request or script loop. Query the IP on startup, store it in a variable, and reuse it.
- User-Agent Headers: Some API services block request scripts that don't declare a user-agent header. It is good practice to include a descriptive header (e.g.
User-Agent: MyPythonScript/1.0).
For developer visual testing, try out our IP Formatter tool to check outputs. If you need to trace geographic location details for any retrieved IP, use our IP Lookup search tool.
Summary
Querying your public IP in Python is straightforward using standard libraries like urllib or third-party packages like requests. Depending on whether your scripts require structured JSON data or plain-text values for simple parsing, you can connect to our matching formats to automate your routing, tracking, and scraper scripts.
Check out these other developer utilities:
- Test client-side formatting on our IP Formatter dashboard.
- Diagnose network settings using our IP Lookup search interface.
