How to Use SOCKS5 Proxies in Python in 2026

A complete developer guide to using SOCKS5 proxies in Python — authenticated and rotating setups with requests and aiohttp, socks5h DNS, and troubleshooting.

Author
ProxyHorizon Team
Published
June 20, 2026
11 min read
Expert-Verified

SOCKS5 is the proxy protocol of choice for developers who need speed, flexibility, and protocol-agnostic routing. Unlike HTTP proxies, SOCKS5 can tunnel any kind of traffic — HTTP, HTTPS, WebSockets, even raw TCP — which makes it a favorite for scraping, automation, and privacy tooling in Python.

Yet SOCKS5 trips up a surprising number of developers. A missing dependency, the wrong URL scheme, or a subtle DNS-leak bug can silently break your setup or expose your real IP. As of 2026, SOCKS5 remains one of the most-searched proxy topics among Python developers precisely because the details matter.

This guide shows you exactly how to use SOCKS5 proxies in Python — from a basic request to authenticated, rotating, and async setups with requests and aiohttp — plus how to avoid DNS leaks and fix the most common errors. Every snippet is copy-paste ready.

What Is a SOCKS5 Proxy?

SOCKS5 is the fifth version of the SOCKS (Socket Secure) protocol. It operates at a lower level than HTTP proxies, forwarding packets between your client and the destination without inspecting or modifying the application-layer data. That makes it protocol-agnostic: it works for web traffic, email, P2P, gaming, and any TCP or UDP connection.

SOCKS5 also adds authentication support and, crucially, the ability to resolve DNS on the proxy side rather than locally. Combined with the trust of a residential proxy, SOCKS5 gives you a fast, flexible, low-detection tunnel — ideal for Python scraping and automation.

Why Use SOCKS5 in Python?

Python developers reach for SOCKS5 for three reasons. First, versatility — the same proxy works across libraries and protocols, not just HTTP. Second, performance — because SOCKS5 does not parse application data, it adds minimal overhead. Third, privacy — with remote DNS resolution it prevents the DNS leaks that can expose your real location even when your traffic is proxied.

For scraping and automation specifically, SOCKS5 pairs perfectly with rotating residential pools, letting you spread requests across many exit IPs while keeping a single, consistent client configuration. It is a core building block for any serious web scraping with Python project.

Prerequisites

You will need Python 3.7+ and a SOCKS5 proxy endpoint (host, port, and optionally a username and password). Most providers give you these in the format host:port:username:password. The standard requests library does not support SOCKS out of the box, so the first step is installing the right extension.

Step-by-Step: Using SOCKS5 Proxies in Python

Follow these steps in order — each builds on the last, from a basic request to a production-ready async, rotating setup.

1Install the Required Packages

The requests[socks] extra pulls in PySocks, which adds SOCKS support to requests.

Bash
pip install requests[socks] pysocks

2Make a Basic SOCKS5 Request

Point both the http and https keys at your SOCKS5 endpoint using the socks5:// scheme.

Python
import requests

proxies = {
    "http": "socks5://proxy.example.com:1080",
    "https": "socks5://proxy.example.com:1080",
}

resp = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=15)
print(resp.json())

3Add Username and Password Authentication

Most commercial SOCKS5 proxies require credentials. Embed them directly in the proxy URL.

Python
proxies = {
    "http": "socks5://username:password@proxy.example.com:1080",
    "https": "socks5://username:password@proxy.example.com:1080",
}

resp = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=15)
print(resp.json())

4Fix DNS Leaks with socks5h

This is the step most developers miss. The plain socks5:// scheme resolves DNS locally, which can leak the hostnames you visit. Use socks5h:// instead to resolve DNS through the proxy.

Python
# socks5h routes DNS through the proxy — prevents DNS leaks
proxies = {
    "http": "socks5h://username:password@proxy.example.com:1080",
    "https": "socks5h://username:password@proxy.example.com:1080",
}

5Reuse Connections with a Session

For multiple requests through the same proxy, a session reuses the underlying connection and is far more efficient.

Python
session = requests.Session()
session.proxies = {
    "http": "socks5h://username:password@proxy.example.com:1080",
    "https": "socks5h://username:password@proxy.example.com:1080",
}

for path in ["/ip", "/user-agent", "/headers"]:
    print(session.get(f"https://httpbin.org{path}", timeout=15).json())

6Rotate Across Multiple SOCKS5 Proxies

Spreading requests across many exit IPs keeps you from being rate-limited. Pick a random proxy per request.

Python
import random
import requests

PROXY_LIST = [
    "socks5h://user:pass@p1.example.com:1080",
    "socks5h://user:pass@p2.example.com:1080",
    "socks5h://user:pass@p3.example.com:1080",
]

def fetch(url):
    proxy = random.choice(PROXY_LIST)
    return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=15)

print(fetch("https://httpbin.org/ip").json())

7Use SOCKS5 Asynchronously with aiohttp

For high-throughput scraping, go async. The aiohttp_socks connector adds SOCKS5 support to aiohttp.

Python
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector

async def fetch(url, proxy_url):
    connector = ProxyConnector.from_url(proxy_url)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get(url) as resp:
            return await resp.text()

result = asyncio.run(
    fetch("https://httpbin.org/ip", "socks5h://user:pass@proxy.example.com:1080")
)
print(result)

That covers the full range — basic, authenticated, leak-proof, pooled, rotating, and async. For more on credentials, see our guide to proxy authentication methods.

How to Verify Your SOCKS5 Proxy Is Working

Before relying on a SOCKS5 setup in production, confirm it actually changes your exit IP. Compare a direct request against a proxied one — if the IPs match, your proxy is not being used.

Python
import requests

proxies = {
    "http": "socks5h://user:pass@proxy.example.com:1080",
    "https": "socks5h://user:pass@proxy.example.com:1080",
}

real = requests.get("https://httpbin.org/ip", timeout=15).json()["origin"]
proxied = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=15).json()["origin"]

print("Real IP:", real)
print("Proxied IP:", proxied)
assert real != proxied, "Proxy not working — IPs match!"

Run this as a quick health check whenever you add new proxies or debug a setup. For a deeper check of speed and anonymity, our proxy testing guide walks through the full process.

SOCKS5 vs HTTP Proxies in Python

Should you use SOCKS5 or an HTTP proxy? Here is how they compare for Python workloads.

Feature

SOCKS5

HTTP Proxy

Protocol Support

Any TCP/UDP traffic

HTTP/HTTPS only

Overhead

Low (no parsing)

Higher (inspects headers)

Remote DNS

Yes (socks5h)

Yes

Header Control

None (pass-through)

Can modify headers

Best For

Versatile, fast tunneling

Web-specific caching/filtering

SOCKS5 Across Python HTTP Libraries

SOCKS5 is not limited to requests. Here is how to enable it in the most popular Python HTTP clients.

Library

SOCKS5 Support

Async

requests

Via requests[socks]

No

httpx

Built-in (socks5://)

Yes

aiohttp

Via aiohttp_socks

Yes

urllib3

Via PySocks

No

Best SOCKS5 Proxy Providers for Python

Your code is only as good as the proxies behind it. These three providers offer reliable SOCKS5 endpoints that work seamlessly with the setups above.

1IPRoyal

Pool:32M+
Uptime:99.9%
Latency:0.8s
Countries:195+
Traffic never expires (pay-as-you-go)
Ethically sourced residential IPs
Crypto and flexible payment options
Affordable entry pricing
Sticky sessions up to 24 hours

IPRoyal offers SOCKS5 support across its ethically sourced residential network, with pay-as-you-go traffic that never expires — ideal for developers who want flexible, affordable SOCKS5 without a big commitment. Coverage spans 195 countries with both HTTP and SOCKS5 protocols.

Its simple credential-based authentication drops straight into the Python examples above, making it a great starting point for SOCKS5 scraping and automation projects.

2PyProxy

Pool:90M+
Uptime:99.9%
Latency:0.5s
Countries:190+
Rotating residential bandwidth from roughly $0.77/GB on commit, with PAYG entry around $3.30/GB
SOCKS5 sold by-IP from ~$0.045 per IP, one of the cheapest unit prices on the market
90M+ residential IPs with city, state, ZIP, and ASN-level targeting on residential plans
Dedicated S5 SOCKS5 client app popular with multi-accounting and antidetect-browser users
Unlimited Residential bandwidth daily plan from ~$79/day for high-throughput single projects
Covers residential, datacenter, ISP, and SOCKS5 in one dashboard, plus standard API access

PyProxy is a standout for SOCKS5 specifically, selling SOCKS5 by the IP at some of the lowest unit prices on the market and offering a dedicated S5 client popular with automation and multi-accounting users. It is a natural fit for developers who need large volumes of SOCKS5 endpoints.

With city, state, and ASN-level targeting on its residential plans, PyProxy gives Python developers fine-grained control over exit locations at a budget-friendly price.

3Decodo

Pool:115M+
Uptime:99.99%
Latency:0.6s
Countries:195+
Huge 97M+ residential IP pool
Beginner-friendly dashboard and documentation
Flexible pay-as-you-go pricing
High success rates on tough targets
Fast 24/7 live chat support
Free trial and money-back guarantee

Decodo (formerly Smartproxy) pairs SOCKS5 support with a huge 115M+ residential pool, 99.99% uptime, and a beginner-friendly dashboard. Its high success rates and clean documentation make it easy to get SOCKS5 working in Python quickly.

For developers who want premium reliability without enterprise complexity, Decodo is an excellent SOCKS5 choice. Browse more options in our proxy directory.

Real-World SOCKS5 Use Cases in Python

SOCKS5 is not just a scraping tool. Here are the most common Python workflows that rely on it.

1Web Scraping and Crawling

The biggest use case. SOCKS5 lets your scraper route requests through residential exit IPs, spreading load across a rotating pool so target sites see ordinary visitors rather than one hammering address. Paired with requests or aiohttp, it keeps success rates high on protected sites while adding minimal latency.

2Multi-Account Automation

Bots that manage multiple accounts assign each identity a distinct SOCKS5 exit IP so platforms cannot link them by network footprint. A sticky SOCKS5 endpoint per account keeps the IP stable across a session, which is essential for avoiding the bans that come from sharing one address across profiles.

3Privacy and Anonymity Tooling

Because SOCKS5 with remote DNS hides both your IP and the hostnames you resolve, it is a building block for privacy scripts, research tools, and anything that must not expose the operator's location. The socks5h scheme is what makes this leak-resistant.

4P2P and Non-HTTP Traffic

Unlike HTTP proxies, SOCKS5 can tunnel any TCP traffic, so Python tools that speak non-HTTP protocols — torrent clients, custom socket apps, database connectors — can all route through the same SOCKS5 endpoint without protocol-specific workarounds.

Using SOCKS5 with Playwright and Selenium

Browser automation frameworks can also route through SOCKS5, with one important caveat: most Chromium-based engines do not support SOCKS5 username and password authentication. For authenticated proxies, use IP whitelisting in your provider dashboard, or run a local proxy bridge that handles the credentials.

With an IP-whitelisted endpoint, Playwright setup is straightforward:

Python
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(
        proxy={"server": "socks5://proxy.example.com:1080"}
    )
    page = browser.new_page()
    page.goto("https://httpbin.org/ip")
    print(page.content())
    browser.close()

Selenium follows the same pattern via a Chrome option: --proxy-server=socks5://proxy.example.com:1080. Because of the auth limitation, residential providers that support IP whitelisting are the smoothest fit for browser automation. For driving headless browsers at scale, our web scraping with Python guide goes deeper.

Troubleshooting Common SOCKS5 Errors in Python

Most SOCKS5 problems come down to a handful of recurring mistakes. Here is how to diagnose and fix them.

1"Missing dependencies for SOCKS support"

This error means PySocks is not installed. Run pip install requests[socks] pysocks and restart your interpreter. The bracketed extra is required even if you think requests is already installed.

2Your Real IP Is Leaking

If a leak test still shows your real location, you are almost certainly using socks5:// instead of socks5h://. The h forces DNS resolution through the proxy. Always use socks5h:// for privacy-sensitive work and verify with a proxy speed and anonymity test.

3Connection Timeouts

Timeouts usually mean a dead proxy, wrong port, or an overloaded endpoint. Always set an explicit timeout, wrap requests in try/except, and rotate to a fresh proxy on failure rather than retrying the same dead IP repeatedly.

4407 Proxy Authentication Required

This means your credentials are missing or wrong. Double-check the username and password in the proxy URL, ensure special characters are URL-encoded, and confirm your IP is whitelisted if the provider uses IP-based authentication.

5Slow Performance

If requests are sluggish, reuse a session instead of creating a new connection each time, run requests asynchronously with aiohttp for concurrency, and choose a provider with low latency. For high-volume jobs, see our guide on building a rotating proxy script in Python.

Best Practices for SOCKS5 in Python

Keep these habits in mind to build robust, leak-free SOCKS5 setups:

  • Always use socks5h — Resolve DNS through the proxy to prevent leaks unless you have a specific reason not to.

  • Set timeouts everywhere — Never make a proxied request without an explicit timeout to avoid hanging on dead proxies.

  • Reuse sessions — Pool connections for repeated requests to the same endpoint for better performance.

  • Rotate and retry — Cycle through a pool and fail over to a fresh IP on errors instead of hammering one proxy.

  • Verify your exit IP — Periodically hit an IP-echo endpoint to confirm rotation is working and your real IP is hidden.

Frequently Asked Questions

The difference is where DNS resolution happens. With socks5:// the hostname is resolved locally on your machine before connecting, which can leak the domains you visit. With socks5h:// the hostname is sent to the proxy and resolved remotely, preventing DNS leaks. For privacy-sensitive scraping and automation, always use socks5h:// in your proxy URLs.
Yes, but not out of the box. You must install the SOCKS extra with pip install requests[socks] pysocks, which adds PySocks support. After that, you simply pass a proxies dictionary with socks5:// or socks5h:// URLs to requests just like you would with an HTTP proxy. Without PySocks installed you will get a missing-dependencies error.
Embed the username and password directly in the proxy URL using the format socks5h://username:password@host:port. Pass that as both the http and https values in your proxies dictionary. If your password contains special characters, URL-encode them. Some providers use IP whitelisting instead of credentials, in which case you add your server IP in the provider dashboard rather than the URL.
Yes. For asyncio-based code, use aiohttp with the aiohttp_socks package, which provides a ProxyConnector you build from a socks5:// URL and pass to your aiohttp ClientSession. The httpx library also supports SOCKS5 natively in both sync and async modes. Async is strongly recommended for high-throughput scraping where you make many concurrent requests.
The most common cause is using socks5:// instead of socks5h://, which resolves DNS locally and can reveal the sites you visit. Switch to socks5h:// to route DNS through the proxy. Also confirm both the http and https keys in your proxies dictionary point to the proxy, and verify with an IP and DNS leak test that your exit IP matches the proxy, not your real location.
Often, yes. Because SOCKS5 operates at a lower level and does not parse or modify application-layer data, it adds less overhead than an HTTP proxy that inspects headers. The real-world difference depends more on the provider's network quality and your proxy location than the protocol itself, but for raw tunneling SOCKS5 is typically the leaner option.
Maintain a list of SOCKS5 proxy URLs and select one per request, for example with random.choice, then pass it in the proxies dictionary. For more control, track success rates per proxy and skip ones that fail. Many providers also offer a single rotating endpoint that automatically assigns a fresh IP on each connection, which removes the need to manage a list yourself.
A 407 error means the proxy rejected your credentials. Check that the username and password in your proxy URL are correct and URL-encoded if they contain special characters. If your provider uses IP-based authentication instead of credentials, make sure your current server IP is added to the allowlist in the provider dashboard. A wrong port can also surface as an auth failure.
Residential SOCKS5 proxies are the safest default for scraping because they use real ISP-assigned IPs that sites trust, combined with SOCKS5's fast, flexible tunneling. Datacenter SOCKS5 proxies are cheaper and faster for low-defense targets. For the hardest sites, mobile SOCKS5 IPs offer the highest trust. Match the proxy type to how aggressively your target blocks automated traffic.

Conclusion: Mastering SOCKS5 Proxies in Python

SOCKS5 gives Python developers a fast, versatile, protocol-agnostic way to route traffic — but the details make or break it. Install requests[socks], prefer socks5h:// to avoid DNS leaks, reuse sessions, rotate across a pool, and go async with aiohttp when you need throughput.

With those patterns in place, SOCKS5 becomes a reliable foundation for scraping, automation, and privacy tooling. Pair your code with a quality residential SOCKS5 provider and you will have a setup that is both fast and hard to detect. The patterns in this guide scale from a single script to a distributed scraping fleet without changing the fundamentals.

Ready to build? Explore SOCKS5-ready providers in our proxy directory, compare options in our proxy comparison tool, or deepen your toolkit with our best residential proxies for web scraping guide.