Python requests SOCKS5 Proxy Examplewith Auth, DNS, Retries & Rotation
Complete guide to using SOCKS5 proxies with Python requests library including authentication, DNS resolution, error handling, and proxy rotation patterns.
Quick Start: Minimal SOCKS5 example
import requests # For credentials with special chars, use URL encoding: # from urllib.parse import quote # PROXY = f"socks5h://{quote('user@123')}:{quote('p@ss!')}@host:port" PROXY = "socks5h://username:password@host:port" # e.g. socks5h://user:pass@1.2.3.4:1080 proxies = {"http": PROXY, "https": PROXY} resp = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=20) resp.raise_for_status() print(resp.json())
Important Notes
- • Install SOCKS support with
pip install "requests[socks]"
(this pulls in PySocks) - •
socks5h
ensures the proxy does DNS resolution. Plainsocks5
resolves locally
Production-Ready Session: Timeouts + Retries (with backoff)
Use a Session, mount an adapter with urllib3.Retry, and share connections efficiently:
import os import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry from urllib.parse import quote # Safe credential handling with environment variables user = quote(os.getenv("PROXY_USER", "")) pw = quote(os.getenv("PROXY_PASS", "")) host = os.getenv("PROXY_HOST", "127.0.0.1") port = int(os.getenv("PROXY_PORT", "1080")) PROXY = f"socks5h://{user}:{pw}@{host}:{port}" if user else f"socks5h://{host}:{port}" session = requests.Session() session.proxies.update({"http": PROXY, "https": PROXY}) retry = Retry( total=5, # total retry attempts connect=5, # retry on connection errors read=5, # retry on read errors status=5, # retry on certain HTTP status codes backoff_factor=0.5, # 0.5, 1, 2, 4... seconds status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["HEAD", "GET", "OPTIONS"] # safe methods only (add POST with caution) ) adapter = HTTPAdapter(max_retries=retry, pool_connections=50, pool_maxsize=50) session.mount("http://", adapter) session.mount("https://", adapter) def fetch(url): return session.get(url, timeout=(5, 30)) if __name__ == "__main__": print(fetch("https://httpbin.org/ip").json())
Pro tip: Retry provides exponential backoff and respects Retry-After headers for robust error handling.
⚠️ POST Safety: We removed POST from default retries. If you must retry POST requests, use idempotency keys and accept the risk of duplicate operations.
The socks5 vs socks5h difference (and when it bites)
socks5://...
Local DNS resolution (your machine looks up the hostname, then asks the proxy to connect to that IP).
socks5h://...
Remote DNS resolution on the proxy (prevents DNS leaks and is required for .onion and some providers).
Some proxy networks even require remote DNS (hostname-only targets), so use socks5h
.
Need Reliable SOCKS5 Proxies?
Get premium mobile proxies with authentic carrier IPs, perfect for your Python automation needs.