Automation & Development

How to Use SOCKS5 Proxies in Python: Requests, HTTPX and Sockets

A hands-on tutorial for sending traffic through a SOCKS5 proxy from Python, covering Requests, HTTPX and low-level sockets, including remote DNS and error handling.

ProxyGrove Editorial · · · 9 min read

Blue code window showing a Python script routing a request through a SOCKS5 proxy

TL;DR: In Python, install the SOCKS extra (requests[socks] or httpx[socks]) and use socks5h:// URLs so the proxy resolves hostnames. Use explicit timeouts, keep credentials in environment variables and test with an IP-echo URL. For raw sockets, PySocks wraps the standard socket module.

Prerequisites and installation

You need Python 3.9 or newer and a SOCKS5 endpoint from your provider (host, port, username, password). ProxyGrove lists SOCKS5 support among its published protocols; the exact endpoints are shown in your account. The code below uses placeholders that you replace with your own values.

Neither Requests nor HTTPX includes SOCKS support in the base install. Install the extras that add it:

pip install "requests[socks]" "httpx[socks]" PySocks

The Requests documentation explains this in its SOCKS section, and HTTPX covers the same ground in its proxies guide.

Choosing the right URL scheme

SchemeWhere DNS is resolvedTypical use
socks5://On your machineTargets that are reachable locally by name
socks5h://On the proxyPreferred when you want the proxy's network to look up names

Use socks5h by default. It avoids sending name lookups from your local network and lets the destination resolve from the proxy's region, which can matter for geo-based content.

Using Requests

import os
import requests

PROXY_URL = "socks5h://{user}:{pw}@{host}:{port}".format(
    user=os.environ["PROXY_USER"],      # YOUR_PROXY_USERNAME
    pw=os.environ["PROXY_PASSWORD"],    # YOUR_PROXY_PASSWORD
    host=os.environ["PROXY_HOST"],      # YOUR_PROXY_HOST
    port=os.environ["PROXY_PORT"],      # YOUR_PROXY_PORT
)

proxies = {"http": PROXY_URL, "https": PROXY_URL}

resp = requests.get("https://example.com/", proxies=proxies, timeout=(5, 30))
print(resp.status_code)

Reading credentials from environment variables keeps them out of version control. If your password contains characters such as @ or :, percent-encode it with urllib.parse.quote before inserting it into the URL.

Using HTTPX

import os
import httpx

proxy_url = "socks5://YOUR_PROXY_USERNAME:YOUR_PROXY_PASSWORD@YOUR_PROXY_HOST:YOUR_PROXY_PORT"

with httpx.Client(proxy=proxy_url, timeout=30.0) as client:
    r = client.get("https://example.com/")
    print(r.status_code)

In HTTPX the proxy argument applies to all requests made through the client. Older releases used a proxies argument instead, so check the version you have installed. For asynchronous code, the same argument works with httpx.AsyncClient, which is helpful when you send many concurrent requests. Keep concurrency modest so the proxy and the target are not overloaded.

Low-level sockets with PySocks

Occasionally you need a plain TCP connection, for example to an SMTP or custom service. PySocks provides a socket class that connects through a SOCKS5 proxy.

import socks

s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "YOUR_PROXY_HOST", 1080, True,
            "YOUR_PROXY_USERNAME", "YOUR_PROXY_PASSWORD")
s.settimeout(15)
s.connect(("example.com", 80))
s.sendall(b"HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
print(s.recv(256))
s.close()

The fourth argument, True, turns on remote DNS resolution. Replace the sample port with your actual SOCKS5 port. The standard library's ssl module can wrap this socket if you need TLS.

Verifying that the proxy is in use

  1. Request an IP-echo endpoint you trust without the proxy and note the address.
  2. Repeat the request with the proxy configured and confirm that a different address appears.
  3. If you use rotating sessions, repeat several times and note how addresses change.
  4. Time the requests so you have a baseline for later debugging.

Error handling and timeouts

Network code should expect failure. Catch requests.exceptions.ProxyError for proxy connection problems, ConnectTimeout and ReadTimeout for slowness, and SSLError for TLS faults. Retry only idempotent requests, and use a small number of attempts with exponential backoff. Always set both a connect and a read timeout; a missing timeout can cause a worker to hang indefinitely. If authentication fails you will usually see a SOCKS authentication error rather than an HTTP 407, as explained in proxy authentication methods.

Concurrency, sessions and connection reuse

Once a single request works, the next challenge is volume. Reuse a requests.Session or an httpx.Client for many requests so that connections and cookies persist, and so that you avoid repeating the SOCKS handshake for every call. Cap concurrency with a semaphore or a bounded thread pool; flooding a proxy gateway with hundreds of simultaneous connections can cause timeouts that look like network failures.

If you use asynchronous code, create one httpx.AsyncClient per proxy identity and close it with an async context manager. For rotating gateways, the same client can serve many tasks, because the gateway changes the exit. For sticky sessions, create a client per session identifier so cookies and exit address stay aligned.

Finally, measure. Record time to connect, time to first byte and total time for a sample of requests. If connection time dominates, you may benefit from keep-alive and fewer, longer-lived clients. If time to first byte dominates, the target or the exit is slow, and changing client code will not help.

Reading proxy settings from configuration

Hard-coding proxy values makes scripts brittle. Read host, port and credentials from environment variables or a configuration file excluded from version control, and build the proxy URL in one helper function that percent-encodes the password. Add a startup check that fetches an IP-echo page and logs the result, so a mis-set variable is caught before a long job begins. Return clear errors when a variable is missing, instead of silently falling back to a direct connection, which could send traffic from the wrong address without anyone noticing.

Unit-testing proxy code without a real proxy

You do not need a live proxy to test your wrapper code. Isolate proxy construction in a small function, such as one that takes a configuration object and returns the URL, and test it for special-character encoding and missing variables. Mock the HTTP client for retry tests so that simulated timeouts and 429 responses exercise backoff logic. Reserve a small, clearly named integration test for the real endpoint, run it manually or on a schedule and keep its credentials out of the shared test configuration.

Common mistakes

  • Forgetting to install the SOCKS extra, which results in an "Missing dependencies for SOCKS support" error.
  • Using socks5:// when remote DNS was intended.
  • Hard-coding credentials in source files.
  • Creating a new session per request and losing connection reuse.
  • Disabling certificate verification to "fix" errors instead of diagnosing them.

Frequently asked questions

Why do I get a 'Missing dependencies for SOCKS support' error?

Install the extra with pip install requests[socks], which pulls in PySocks.

What is the difference between socks5 and socks5h in Requests?

With socks5h the proxy resolves the hostname, while with socks5 your machine resolves it first.

Does SOCKS5 encrypt my Python traffic?

No. SOCKS5 forwards bytes. Use HTTPS URLs so TLS protects the content end to end.

Can I use authentication with SOCKS5?

Yes. Username and password authentication is defined by RFC 1929, and libraries accept credentials in the URL or as parameters.

How should I store proxy credentials?

Use environment variables or a secrets manager, and never commit them to a repository.

Conclusion

Python makes SOCKS5 straightforward once the extras are installed: use socks5h, set timeouts, keep credentials out of code and verify with an IP echo. From there you can plug the same proxy into larger tools; see the guide to proxies for web scraping and the integrations directory for browser automation options.

References

About the author

ProxyGrove Editorial

ProxyGrove Editorial publishes practical guides on proxy technology, automation, and responsible network workflows for international teams.

Sẵn sàng tìm giải pháp proxy phù hợp?

Explore ProxyGrove plans, then apply credentials in your tools with our Integrations guides.