Using SOCKS5 Proxies with aiohttp

aiohttp's proxy argument only speaks HTTP. Install aiohttp-socks, hand the session a ProxyConnector, and set rdns so DNS resolves at the proxy.

aiohttp's proxy= argument speaks only the HTTP proxy protocol. Current releases do not reject a socks5:// URL there: they send an ordinary HTTP proxy request to the SOCKS5 port, the listener closes the connection, and the call fails with ServerDisconnectedError (only aiohttp 3.7 and older raised ValueError: Only http proxies are supported). SOCKS5 goes in through a connector instead, supplied by the aiohttp-socks package.

pip install aiohttp aiohttp-socks
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector

async def main():
    connector = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@HOST:PORT")
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://api.ipify.org?format=json") as r:
            print(await r.json())

asyncio.run(main())

Fill in the SOCKS5 port, which the Proxies page shows once the Connect card is switched to SOCKS5 (or in the residential card's SOCKS5 Port field); the HTTP port on the same host will not complete the handshake. The username and password are the ones you already use. A free account cannot open SOCKS5, so this needs a paid plan from the pricing page. If the script prints the proxy's address, the connector works; the sections below keep it working under load.

Why the connector, not the proxy argument

An HTTP proxy is reached over HTTP: the client sends CONNECT target:443 and the proxy relays bytes from there. SOCKS5 negotiates in binary before any HTTP exists, so aiohttp cannot express it in a request option. A connector is aiohttp's socket factory, responsible for producing a connected transport for a host, which is exactly the layer where the SOCKS5 handshake belongs. Once the session has a ProxyConnector, every request through it is proxied and individual calls need no proxy= at all.

Where DNS happens: rdns

In curl and requests, socks5h:// means "resolve at the proxy" and socks5:// means "resolve locally". aiohttp-socks does not follow that convention (checked on aiohttp-socks 0.12): it rejects socks5h:// with ValueError: Invalid scheme component: socks5h, and a socks5:// URL already sends the hostname to the proxy, because the rdns setting defaults to on for SOCKS5. To make the choice explicit, pass it as an argument:

from aiohttp_socks import ProxyConnector, ProxyType

connector = ProxyConnector(
    proxy_type=ProxyType.SOCKS5,
    host="HOST",
    port=PORT,
    username="USERNAME",
    password="PASSWORD",
    rdns=True,   # resolve at the proxy
)

Leave rdns on. With rdns=False, every hostname is looked up on your own machine before the connector dials the proxy, which leaks the lookups and picks servers near you instead of near the exit. The SOCKS5 setup guide explains the protocol side.

One session, built once

async with aiohttp.ClientSession(...) inside a per-URL coroutine closes its connector on exit, so every URL pays a new TCP connection and a new SOCKS5 handshake. Build the session once and pass it down:

import aiohttp
from aiohttp_socks import ProxyConnector

class Client:
    def __init__(self, proxy_url: str):
        self._proxy_url = proxy_url
        self._session: aiohttp.ClientSession | None = None

    async def __aenter__(self):
        connector = ProxyConnector.from_url(self._proxy_url, limit=20, ttl_dns_cache=300)
        self._session = aiohttp.ClientSession(
            connector=connector,
            timeout=aiohttp.ClientTimeout(total=45, connect=15, sock_read=30),
        )
        return self

    async def __aexit__(self, *exc):
        await self._session.close()

    async def get(self, url: str) -> str:
        async with self._session.get(url) as r:
            r.raise_for_status()
            return await r.text()

limit=20 caps concurrent connections through the connector. aiohttp's default is 100 per connector, and limit=0 removes the cap entirely, so size it to what the plan should carry rather than to the length of your URL list.

The timeout is split on purpose. connect covers reaching the proxy and completing the handshake; sock_read covers silence between chunks once data is flowing. A single total timeout cannot tell a proxy that never finishes negotiating from a target that is slow to send a large body, and through a proxy there are two hops that can stall.

Rotating across a pool

With several exits, hold one session per proxy and cycle them:

import itertools

class Pool:
    def __init__(self, proxy_urls: list[str]):
        self._sessions = [
            aiohttp.ClientSession(connector=ProxyConnector.from_url(u, limit=10))
            for u in proxy_urls
        ]
        self._cycle = itertools.cycle(self._sessions)

    def next(self) -> aiohttp.ClientSession:
        return next(self._cycle)

    async def close(self):
        for s in self._sessions:
            await s.close()

Keep Pool for static addresses. A gateway needs a single ClientSession: the connector's pooled sockets each hold the exit they opened with, ProxyConnector.from_url(url, force_close=True) gives every request its own socket and so its own exit, and a session segment in the username holds one exit across sockets.

A ClientSession also owns a cookie jar, so work that depends on a target's cookie belongs on one session and one exit for as long as that state matters (sticky versus rotating sessions).

Errors

  • ProxyConnectionError: the SOCKS5 endpoint did not accept a TCP connection. Check the host and port; this happens before authentication, so credentials are not implicated.
  • ProxyError after connecting: the negotiation was refused, most often on credentials. Rule out the HTTP port first, then a free-tier account.
  • ProxyTimeoutError: the handshake began and did not finish. Try a different exit before retrying the same one.
  • aiohttp.ClientResponseError with status 407: the request reached an HTTP proxy instead of the connector, through a proxy= argument on the call or trust_env=True picking up HTTPS_PROXY. Remove whichever it is; fixing 407 Proxy Authentication Required covers the other causes.

Confirm the proxy is applied

The one check worth trusting is the address the destination reports. Run the first example in this guide against https://api.ipify.org?format=json: if it prints your own address, a session somewhere in the codebase was created without the connector, which is the case for keeping a single client object.

Still choosing a product for the code? SOCKS5 proxies for aiohttp: which proxy type to use matches rotating, residential, dedicated and shared to the jobs aiohttp usually does.