Last modified: Sep 13, 2026
Get Current IP Address in Python
Finding your current IP address in Python is a common task for developers. Whether you're building a network tool or debugging a connection, knowing your IP is essential. This guide explains several methods to get your current IP address using Python. Each method includes example code and output for clarity.
Why Get Your IP Address?
Your IP address identifies your device on a network. It helps in tracking location, managing access, and diagnosing connectivity issues. In Python, retrieving your public or local IP address can be useful for logging, security, and automation tasks.
Method 1: Using the socket Library
The socket module is part of Python's standard library. It allows you to retrieve your local IP address by connecting to an external server.
import socket
def get_local_ip():
# Create a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Connect to an external server (no data is sent)
s.connect(("8.8.8.8", 80))
# Get the local IP address
ip = s.getsockname()[0]
finally:
# Close the socket
s.close()
return ip
# Print the local IP address
print("Local IP Address:", get_local_ip())
Local IP Address: 192.168.1.5
This method returns your local network IP. It does not send any data to the server. The connection is only used to determine the routing interface.
Method 2: Using the requests Library
To get your public IP address, use the requests library. It fetches your IP from a web service.
import requests
def get_public_ip():
# Send a GET request to a public IP API
response = requests.get("https://api.ipify.org")
# Return the response text (your public IP)
return response.text
# Print the public IP address
print("Public IP Address:", get_public_ip())
Public IP Address: 203.0.113.45
This method retrieves your public IP address from the internet. You need to install the requests library first using pip install requests.
Method 3: Using the urllib Library
If you prefer not to install external libraries, use Python's built-in urllib module.
import urllib.request
def get_public_ip_urllib():
# Open a URL that returns the public IP
with urllib.request.urlopen("https://api.ipify.org") as response:
# Read and decode the response
ip = response.read().decode("utf-8")
return ip
# Print the public IP address
print("Public IP Address:", get_public_ip_urllib())
Public IP Address: 203.0.113.45
This approach uses only standard library tools. It is ideal for lightweight scripts or environments without additional packages.
Choosing the Right Method
Select a method based on your needs:
- For local IP: Use the
socketmethod. - For public IP: Use
requestsorurllib. - For no dependencies: Use
urllib.
Handling Errors
Network operations can fail due to connectivity issues. Always wrap your code in a try-except block.
import requests
def safe_get_public_ip():
try:
# Attempt to fetch the public IP
response = requests.get("https://api.ipify.org", timeout=5)
response.raise_for_status()
return response.text
except requests.RequestException as e:
# Handle any request-related errors
return f"Error: {e}"
# Print the result
print(safe_get_public_ip())
Public IP Address: 203.0.113.45
Adding error handling makes your code more robust. It prevents crashes when the network is unavailable.
Conclusion
Retrieving your IP address in Python is straightforward using socket, requests, or urllib. Choose the method that fits your project's needs. For local IPs, use socket. For public IPs, prefer requests or urllib. Always include error handling for reliability.