Last modified: Apr 27, 2025 By Alexander Williams
Python Requests: Set Custom Source IP
When making HTTP requests in Python, you may need to specify a custom source IP address. This is useful for testing, scraping, or routing traffic.
Why Set a Custom Source IP?
Setting a custom source IP helps in network testing, load balancing, and bypassing IP-based restrictions. It's also useful when working with multiple network interfaces.
For related IP operations, see our guide on Python Generate Random IP Addresses.
Prerequisites
You'll need Python installed and the requests
library. Install it with pip:
pip install requests
Method 1: Using Source Address Parameter
The requests
library supports binding to a specific IP through the source_address parameter:
import requests
response = requests.get(
'https://example.com',
source_address=('192.168.1.100', 0)
)
print(response.status_code)
Note: This requires root privileges on Linux systems. The second tuple element (0) lets the OS choose a random port.
Method 2: Using Session Objects
For multiple requests, create a session with your source IP:
import requests
session = requests.Session()
session.source_address = ('10.0.0.5', 0)
response = session.get('https://example.com')
print(response.text[:100]) # Print first 100 characters
Method 3: Using Proxies
For more control, use proxies with your desired IP:
proxies = {
'http': 'http://192.168.1.100:8080',
'https': 'http://192.168.1.100:8080'
}
response = requests.get('https://example.com', proxies=proxies)
print(response.headers)
Learn more about IP handling in our Python: Detect Private vs Public IP Address guide.
Error Handling
Always handle potential errors when working with custom IPs:
try:
response = requests.get('https://example.com', source_address=('192.168.1.100', 0))
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
Verifying Your Source IP
To verify your outgoing IP, use a service like httpbin:
response = requests.get('https://httpbin.org/ip')
print(f"Current IP: {response.json()['origin']}")
Current IP: 192.168.1.100
For advanced network operations, check our Python Socket: Bind to Specific IP Address tutorial.
Conclusion
Setting a custom source IP in Python Requests is straightforward. Use source_address
for direct binding or proxies for more flexibility.
Remember to handle errors and verify your configuration. These techniques are valuable for network testing and web scraping projects.