A raw TCP test checks a proxy without a library, by sending the protocol lines and bytes over a socket by hand. The test opens four layers in order: the TCP connection, the CONNECT or SOCKS5 handshake, TLS and the target request. Each layer has its own errors. In a library, those errors often collapse into a single exception message. This post covers the port check, a hand-written CONNECT request, the TLS handshake inside the tunnel and the SOCKS5 bytes.
TCP port check
The first layer asks one thing: is anything listening on the proxy's port? socket.create_connection resolves the address and performs the TCP handshake. No proxy protocol is spoken at this step yet.
import socket
import time
HOST, PORT = "pr.proxynet.io", 8000
t0 = time.perf_counter()
try:
with socket.create_connection((HOST, PORT), timeout=5) as s:
ms = (time.perf_counter() - t0) * 1000
print(f"TCP open: {s.getpeername()} ({ms:.0f} ms)")
except socket.gaierror as e:
print("DNS error:", e)
except ConnectionRefusedError:
print("Port closed: the other side refused the connection")
except TimeoutError:
print("Timeout: the packet got no answer")The three exceptions point to three separate problems. gaierror says the host name could not be resolved. ConnectionRefusedError says you reached the machine, but nothing listens on that port. TimeoutError shows that packets are dropped somewhere: a firewall, a wrong IP or a closed network. In our test, a closed local port refused at once, while the documentation address 192.0.2.1 timed out after 5 seconds.
On Windows, PowerShell asks the same question:
Test-NetConnection pr.proxynet.io -Port 8000The TcpTestSucceeded : True line in the output means the port is open. Add -InformationLevel Quiet and it returns only True or False. An open port does not prove the proxy works. It only says you can move to the next layer. Checking IP, location and speed is a separate job, covered in our post on how to test a proxy.
A hand-written CONNECT request
On an HTTP proxy, the tunnel opens with a plain-text CONNECT request written by the client. The request has three lines: target host and port, the Host header and the auth header. A blank line ends it.
import base64
import socket
PROXY = ("pr.proxynet.io", 8000)
TARGET = "example.com:443"
token = base64.b64encode(b"user:pass").decode()
request = (
f"CONNECT {TARGET} HTTP/1.1\r\n"
f"Host: {TARGET}\r\n"
f"Proxy-Authorization: Basic {token}\r\n"
"\r\n"
)
s = socket.create_connection(PROXY, timeout=10)
s.sendall(request.encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = s.recv(1)
if not chunk:
break
head += chunk
print(head.decode("latin-1"))The Basic value is the Base64 form of the username:password text. For user:pass it is dXNlcjpwYXNz. The password itself goes into Base64. Percent-encoding such as %40, which you use in a proxy URL, does not apply to this header: a pass@123 password is encoded as is.
The response header is read byte by byte. It is slow, but it does not swallow the first byte after the blank line. That byte already belongs to the tunnel. We explained the general flow of the tunnel in our HTTP CONNECT post. What matters here is the first line:
| Status line | Meaning | Next step |
|---|---|---|
200 Connection established | Tunnel open | Switch to TLS |
407 Proxy Authentication Required | Credentials missing or wrong | Check the Base64 value |
403 Forbidden | Proxy rejects this host or port | Ask about the port rule |
502 Bad Gateway | Proxy could not reach the target | Check target name and port |
In our test, a wrong password brought 407 and a Proxy-Authenticate: Basic realm="test" header. Our test proxy allowed only 443, so example.com:8443 returned 403. For a domain that does not exist, the proxy returned 502 once its own 10-second limit ran out. When the client timeout was also 10 seconds, the client raised TimeoutError first. Keep the client timeout longer than the proxy's, or you will see a meaningless timeout instead of 502.
TLS handshake in the tunnel
After 200, the socket behaves like a plain TCP connection to the target site. You build TLS on top of the same socket yourself. In Python, that means ssl.create_default_context() and a call to SSLContext.wrap_socket.
import ssl
# s: the socket that returned "200" in step 2, head: the response header
if not head.startswith((b"HTTP/1.1 200", b"HTTP/1.0 200")):
raise SystemExit("Tunnel not open, do not switch to TLS")
ctx = ssl.create_default_context()
tls = ctx.wrap_socket(s, server_hostname="example.com")
print("TLS:", tls.version(), tls.cipher()[0])
print("Certificate:", dict(x[0] for x in tls.getpeercert()["subject"]))
tls.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
print(tls.recv(4096).split(b"\r\n", 1)[0].decode())The ssl.wrap_socket() function from older examples was removed in Python 3.12. In Python 3.13.17 the name did not exist in the module. The old function sent no SNI and did not verify the host name. server_hostname does both jobs at once: it writes the name into the SNI field and verifies the certificate against that name.
In our test, TLS 1.3 came up through the tunnel, the certificate's commonName was example.com and the request returned HTTP/1.1 200 OK. With a name the site did not recognize in server_hostname, the site cut the handshake with an SSLV3_ALERT_HANDSHAKE_FAILURE alert. This error comes from the site at the far end of the tunnel, not from the proxy.
Without writing Python, OpenSSL does the same two steps:
openssl s_client \
-proxy pr.proxynet.io:8000 \
-proxy_user user -proxy_pass pass:pass \
-connect example.com:443 \
-servername example.com -briefThe -proxy_pass value uses OpenSSL's passphrase format, so it starts with pass:. On success, the output prints the CONNECTION ESTABLISHED, Protocol version and Verification: OK lines. With a wrong password it prints HTTP CONNECT failed, reason=407 and never reaches TLS. s_client only speaks HTTP CONNECT. For SOCKS5, you send the bytes below by hand.
SOCKS5 handshake bytes
SOCKS5 is a byte protocol, not a text one, and the tunnel opens in three rounds: method selection, the username and password subnegotiation, and the CONNECT request. The first two are defined in RFC 1928 and RFC 1929, the reply codes in RFC 1928.
import socket
import struct
PROXY = ("pr.proxynet.io", 8000)
USER, PASS = b"user", b"pass"
HOST, PORT = b"example.com", 443
def recv_exact(s, n):
data = b""
while len(data) < n:
chunk = s.recv(n - len(data))
if not chunk:
raise ConnectionError("Proxy closed the connection")
data += chunk
return data
s = socket.create_connection(PROXY, timeout=10)
# 1. Method selection: version 5, one method, 0x02 = username/password
s.sendall(b"\x05\x01\x02")
ver, method = recv_exact(s, 2)
print("Method reply:", hex(ver), hex(method))
if method == 0xFF:
raise SystemExit("Proxy accepted none of the offered methods")
# 2. Username/password subnegotiation (RFC 1929)
s.sendall(b"\x01" + bytes([len(USER)]) + USER + bytes([len(PASS)]) + PASS)
auth_ver, status = recv_exact(s, 2)
print("Auth reply:", hex(auth_ver), hex(status))
if status != 0x00:
raise SystemExit("Username or password rejected")
# 3. CONNECT: command 0x01, address type 0x03 = domain name
s.sendall(b"\x05\x01\x00\x03" + bytes([len(HOST)]) + HOST + struct.pack("!H", PORT))
ver, rep, _, atyp = recv_exact(s, 4)
addr_len = {0x01: 4, 0x04: 16}.get(atyp) or recv_exact(s, 1)[0]
recv_exact(s, addr_len + 2) # BND.ADDR + BND.PORT
print("CONNECT reply:", hex(rep))The first byte of the subnegotiation is 0x01, not 0x05. This is the common mistake. Address type 0x03 sends the domain name to the proxy, and the proxy resolves DNS. That is what the socks5h:// scheme does. The length of the BND.ADDR field in the reply depends on the address type. Skip reading it and the leftover bytes mix into the start of TLS.
| Reply | Meaning |
|---|---|
Method 0xFF | None of your offered methods was accepted |
Auth status other than 0x00 | Username or password wrong, proxy closes the connection |
CONNECT 0x00 | Tunnel open |
CONNECT 0x02 | A proxy rule does not allow this connection |
CONNECT 0x04 / 0x05 | Target host unreachable / target port refused the connection |
In our test, with correct credentials the replies were 0x05 0x02, 0x01 0x00 and 0x00. With a wrong password the auth reply was 0x01 0x01 and the connection closed. When we offered only the 0x00 (no auth) method, the proxy returned 0xFF. On a closed target port the CONNECT reply was 0x05. After the 0x00 reply we applied the TLS code from the previous section to the same socket, and the request returned HTTP/1.1 200 OK. The Proxynet SOCKS5 Proxy uses this handshake for TCP; for UDP there is a separate UDP ASSOCIATE command.
Wrong protocol on the wrong port
When the HTTP and SOCKS5 ports get mixed up, the two sides do not understand each other and no error message arrives. In our test we sent a CONNECT line to the SOCKS5 port. The proxy could not read the first byte as 0x05, closed the connection, and the client got an empty response. When we sent a SOCKS5 greeting to the HTTP port, the proxy waited for the header to end and the client timed out. Real proxies may also return 400 here.
If you see an empty response or a timeout in the first round, the problem is not the credentials. It is the match between port and protocol.
Debugging
Look at which layer the error comes from, then fix only that layer. The table below ties each symptom to a layer.
| Symptom | Layer | First check |
|---|---|---|
gaierror | DNS | Spelling of the proxy host name |
ConnectionRefusedError | TCP | Port number |
TimeoutError on connect | TCP | Firewall, IP whitelist |
407 or auth 0x01 | Proxy auth | Base64 value, password |
403 or CONNECT 0x02 | Proxy rule | Allowed ports |
502 or CONNECT 0x04 / 0x05 | Between proxy and target | Target host and port |
| Empty response, timeout in the first round | Protocol | HTTP or SOCKS5 |
SSLError, SSLCertVerificationError | TLS | server_hostname, system clock |
The same stages show up line by line in curl -v output. The raw socket shows, byte by byte, the part that curl summarizes. We covered the curl side in our post on reading proxy logs.
How we tested
We ran the tests on December 2, 2026, on Windows 11 with Python 3.13.17. A local test proxy we wrote in Python listened on two ports. The HTTP port required Basic auth for user:pass and opened CONNECT only to 443. The SOCKS5 port required RFC 1929 auth. The proxy logged every incoming line and byte.
We ran the code from this post in a separate process for each scenario, changing only the address and port to local values. The target was example.com:443. For openssl s_client we used OpenSSL 3.5.9 from Git for Windows, and for the port test the Test-NetConnection command in Windows PowerShell 5.1. We left the measured times out of the post because the connection was local.
The bottom line
Test the proxy layer by layer: first the port, then the CONNECT or SOCKS5 reply, TLS last. Do not move on before reading each step's reply. Above all, make sure the protocol you write in the proxy address matches the port. When you need an exit IP with location targeting, Residential Proxy works with the same CONNECT and SOCKS5 flow.
Sources
- RFC 9110, HTTP Semantics, §9.3.6 CONNECT: rfc-editor.org
- RFC 1928, SOCKS Protocol Version 5: rfc-editor.org
- RFC 1929, Username/Password Authentication for SOCKS V5: datatracker.ietf.org
- ssl module, SSLContext.wrap_socket: docs.python.org
- openssl-s_client, -proxy options: docs.openssl.org
Frequently asked questions
Can you test a proxy with telnet?
Yes, but only the first layer. Telnet shows whether the port is open and lets you type the CONNECT line by hand. Building the Base64 header, sending SOCKS5 bytes and setting up TLS in the tunnel are not practical with telnet, though. On Windows, Test-NetConnection is easier for the port check, and a Python socket for the steps after it.
How do you build the Proxy-Authorization header?
Encode the username:password text in Base64 and put Basic in front of it. In Python, base64.b64encode(b"user:pass").decode() gives dXNlcjpwYXNz. Characters such as @ in the password are not percent-encoded in this header; they go into the encoding as they are. Base64 is not encryption. If the connection between you and the proxy is plain TCP, the header can be read on the network.
CONNECT returned 200 but the page does not load. Where is the problem?
At the other end of the tunnel. 200 says the proxy opened a TCP connection to the target. Any error after that comes from the TLS handshake or the target site. Check that the server_hostname value matches the target name, that the system clock is correct and what the target site responds. Proxy auth is no longer involved at this stage.
Why does a SOCKS5 test send 0x05 0x01 0x02 first?
Because that is method selection. The first byte is the version (0x05), the second says how many methods you offer, the third is the method itself. 0x02 means username and password. The proxy replies with the method it chose. If 0xFF comes back, it accepted none of your methods and the client should close the connection.
Why doesn't ssl.wrap_socket work?
Because it was removed in Python 3.12. Instead, create a context with ssl.create_default_context() and call ctx.wrap_socket(sock, server_hostname="example.com"). This sends SNI and verifies the certificate against the host name. The old function did neither. In our test on Python 3.13.17, the name ssl.wrap_socket did not exist in the module.
Can openssl s_client be used with a SOCKS5 proxy?
No. The -proxy option only sends an HTTP CONNECT request. For credentials you add -proxy_user and -proxy_pass, with the password written after a pass: prefix. To test a SOCKS5 tunnel, send the handshake bytes with a Python socket, and after the 0x00 reply turn the same socket into TLS with SSLContext.wrap_socket.




