---
title: "How to Test SOCKS5 UDP Support: Python Checker and Troubleshooting"
author: "Omar Rifai"
published: "2025-07-25"
modified: "2026-09-22"
tags: ["Proxies & Anonymity", "Tech Tutorials & Programming"]
url: "https://proxidize.com/blog/test-udp-over-socks"
source: "proxidize"
---

# How to Test SOCKS5 UDP Support: Python Checker and Troubleshooting

The most reliable first test for SOCKS5 UDP support is a direct UDP ASSOCIATE probe—not a browser, VoIP app, or system-wide tunnel. The Python checker below negotiates SOCKS5, requests a UDP relay, sends a DNS query through it, and validates both the returned SOCKS5 envelope and DNS answer. It does not print proxy credentials, and it does not treat an arbitrary packet or a timeout as a definitive result.

## Quick Answer

Save the checker in this guide as socks5_udp_check.py, then run:

```bash
python3 socks5_udp_check.py \
  --proxy-host proxy.example.test \
  --proxy-port 1080
```

If the proxy requires username/password authentication, load SOCKS5_USERNAME and SOCKS5_PASSWORD through your existing secrets workflow before running the command. Do not put a password in the command itself, a proxy URL, source code, screenshots, or logs.

A passing result means the proxy accepted UDP ASSOCIATE, relayed one DNS query to the selected resolver, returned a valid unfragmented SOCKS5 UDP packet, and carried a structurally complete DNS response. The accepted IPv4 answer must belong to the queried name or a CNAME chain rooted at it. A pass does **not** prove that every UDP destination or protocol is allowed.

A timeout is inconclusive. It may reflect a blocked resolver, local firewall, routing problem, source-address restriction, packet loss, or proxy policy—not necessarily a lack of SOCKS5 UDP support.

## Key Takeaways

- SOCKS5 TCP CONNECT support does not prove that the same endpoint permits UDP ASSOCIATE.
- A valid test must inspect the relay reply, SOCKS5 UDP envelope, complete DNS message, and answer ownership—not merely receive a datagram.
- Keep the TCP control connection open for the association, and never include proxy credentials in test output.
- Treat silence as unresolved. Isolate routing, firewall, destination, proxy-policy, and packet-loss variables before using tun2socks or an application-level test.

## What Counts as a Valid SOCKS5 UDP Test?

A useful checker validates each layer independently. Otherwise, it can report a false pass after receiving an unrelated or malformed datagram—or a false failure when only the chosen DNS resolver is unreachable.

| Test stage | What the checker verifies | What a pass establishes | What a failure establishes |
|---|---|---|---|
| TCP connection | The SOCKS5 control endpoint is reachable | The client can reach the proxy over TCP | A reachability, DNS, port, or firewall problem exists before UDP testing begins |
| Method negotiation | The server selects a method the client offered | SOCKS5 negotiation is valid | The endpoint, version, or available authentication method is wrong |
| Authentication | Username/password authentication succeeds when configured | The supplied credentials are accepted | Authentication failed; it says nothing about UDP relay support |
| `UDP ASSOCIATE` | The server returns success and a usable relay address/port | The server accepted the association request | The reply code identifies a command or policy failure |
| Relay packet | The reply comes from the negotiated relay and has valid reserved, fragment, address, and port fields | One unfragmented SOCKS5 UDP response was structurally valid | The returned datagram cannot be trusted as a valid SOCKS5 UDP response |
| DNS response | Transaction ID, response flags, question, return code, declared sections, CNAME chain, and A-record owner are valid | The selected DNS request completed through the relay | The payload was malformed, incomplete, unrelated to the query, or returned no valid A record for the requested name chain |

The [SOCKS5 specification, RFC 1928](https://www.rfc-editor.org/rfc/rfc1928.html), defines UDP ASSOCIATE as command 0x03. It also defines the UDP request/reply envelope: two reserved bytes, a fragment byte, an address type, destination address, destination port, and application data.

## How SOCKS5 UDP ASSOCIATE Works

The test uses two related connections:

```bash
Python checker ── TCP ──> SOCKS5 control endpoint
                     1. Negotiate authentication
                     2. Request UDP ASSOCIATE
                     3. Keep this TCP connection open

Python checker ── UDP/SOCKS5 envelope ──> negotiated relay ── UDP ──> DNS resolver
Python checker <─ UDP/SOCKS5 envelope ─── negotiated relay <─ UDP ─── DNS resolver
```

The TCP connection is not just setup traffic. RFC 1928 says the UDP association ends when the TCP connection that requested it terminates. A test that closes the control socket before waiting for the UDP reply can create its own failure.

The proxy's successful UDP ASSOCIATE reply includes the address and port of its UDP relay. The client sends the DNS query to that relay—not directly to the resolver—and wraps it in the SOCKS5 UDP header. The proxy returns the resolver's reply in the same kind of envelope.

This checker sets FRAG to zero and rejects nonzero FRAG values in replies. RFC 1928 makes fragmentation support optional for clients and requires clients without it to drop fragmented datagrams.

## Before You Run the Checker

You need:

- Python 3.10 or newer.
- A SOCKS5 hostname and port.
- A username and password only if the endpoint requires them.
- An approved UDP DNS resolver reachable from the proxy. The default is Google Public DNS at 8.8.8.8:53, whose published addresses and UDP/TCP service are documented by [Google Public DNS](https://developers.google.com/speed/public-dns/docs/using).
- Permission to test the proxy and destination.

The script uses only Python's standard library. It makes one A-record query for example.com unless you override --name. Choose a domain and resolver you are allowed to query, and keep retries bounded.

For authenticated access, let your password manager, CI secret store, or runtime secrets system populate SOCKS5_USERNAME and SOCKS5_PASSWORD. If you need a one-time local prompt that avoids putting the values in shell history, use:

```bash
read -r -p 'SOCKS5 username: ' SOCKS5_USERNAME
read -r -s -p 'SOCKS5 password: ' SOCKS5_PASSWORD
printf '\n'
export SOCKS5_USERNAME SOCKS5_PASSWORD
```

Clear the variables from the shell when the test is complete:

```bash
unset SOCKS5_USERNAME SOCKS5_PASSWORD
```

Username/password authentication is defined by [RFC 1929](https://www.rfc-editor.org/rfc/rfc1929.html). That subnegotiation does not encrypt the credentials by itself, so use it only across a trusted network path or an additional protected transport appropriate to your environment.

## Python SOCKS5 UDP Checker

Save the following exact script as socks5_udp_check.py:

```python
#!/usr/bin/env python3
"""Validate a SOCKS5 UDP ASSOCIATE path with one DNS A query."""

from __future__ import annotations

import argparse
import ipaddress
import json
import os
import secrets
import socket
import struct
import sys
import time
from dataclasses import dataclass


SOCKS_REPLY = {
    0x01: "general SOCKS server failure",
    0x02: "connection not allowed by ruleset",
    0x03: "network unreachable",
    0x04: "host unreachable",
    0x05: "connection refused",
    0x06: "TTL expired",
    0x07: "command not supported",
    0x08: "address type not supported",
}


@dataclass
class CheckError(Exception):
    stage: str
    message: str
    timeout: bool = False

    def __str__(self) -> str:
        return self.message


def receive_exact(sock: socket.socket, size: int) -> bytes:
    chunks: list[bytes] = []
    remaining = size
    while remaining:
        chunk = sock.recv(remaining)
        if not chunk:
            raise ConnectionError("the SOCKS5 control connection closed early")
        chunks.append(chunk)
        remaining -= len(chunk)
    return b"".join(chunks)


def encode_socks_address(host: str) -> tuple[int, bytes]:
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        encoded = host.encode("idna")
        if not 1 <= len(encoded) <= 255:
            raise ValueError("SOCKS5 domain names must contain 1 to 255 bytes")
        return 0x03, bytes([len(encoded)]) + encoded

    if address.version == 4:
        return 0x01, address.packed
    return 0x04, address.packed


def receive_socks_address(sock: socket.socket, address_type: int) -> str:
    if address_type == 0x01:
        return socket.inet_ntop(socket.AF_INET, receive_exact(sock, 4))
    if address_type == 0x04:
        return socket.inet_ntop(socket.AF_INET6, receive_exact(sock, 16))
    if address_type == 0x03:
        length = receive_exact(sock, 1)[0]
        if length == 0:
            raise ValueError("SOCKS5 returned an empty domain name")
        return receive_exact(sock, length).decode("idna")
    raise ValueError(f"SOCKS5 returned unsupported address type 0x{address_type:02x}")


def decode_socks_address(packet: bytes, offset: int, address_type: int) -> tuple[str, int]:
    if address_type == 0x01:
        end = offset + 4
        if end > len(packet):
            raise ValueError("truncated IPv4 address in SOCKS5 UDP packet")
        return socket.inet_ntop(socket.AF_INET, packet[offset:end]), end

    if address_type == 0x04:
        end = offset + 16
        if end > len(packet):
            raise ValueError("truncated IPv6 address in SOCKS5 UDP packet")
        return socket.inet_ntop(socket.AF_INET6, packet[offset:end]), end

    if address_type == 0x03:
        if offset >= len(packet):
            raise ValueError("missing domain length in SOCKS5 UDP packet")
        length = packet[offset]
        start = offset + 1
        end = start + length
        if length == 0 or end > len(packet):
            raise ValueError("invalid domain name in SOCKS5 UDP packet")
        return packet[start:end].decode("idna"), end

    raise ValueError(f"unsupported SOCKS5 UDP address type 0x{address_type:02x}")


def negotiate_authentication(
    control: socket.socket,
    username: str | None,
    password: str | None,
) -> str:
    if (username is None) != (password is None):
        raise CheckError(
            "configuration",
            "set both SOCKS5_USERNAME and SOCKS5_PASSWORD, or set neither",
        )

    if username is None:
        methods = bytes([0x00])
    else:
        methods = bytes([0x02])

    control.sendall(bytes([0x05, len(methods)]) + methods)
    version, method = receive_exact(control, 2)

    if version != 0x05:
        raise CheckError("method_negotiation", f"unexpected SOCKS version 0x{version:02x}")
    if method == 0xFF:
        raise CheckError("method_negotiation", "the proxy accepted none of the offered methods")
    if method not in methods:
        raise CheckError(
            "method_negotiation",
            f"the proxy selected method 0x{method:02x}, which the client did not offer",
        )

    if method == 0x00:
        return "none"

    assert username is not None and password is not None
    username_bytes = username.encode("utf-8")
    password_bytes = password.encode("utf-8")
    if not 1 <= len(username_bytes) <= 255:
        raise CheckError("configuration", "the username must contain 1 to 255 bytes")
    if not 1 <= len(password_bytes) <= 255:
        raise CheckError("configuration", "the password must contain 1 to 255 bytes")

    request = (
        bytes([0x01, len(username_bytes)])
        + username_bytes
        + bytes([len(password_bytes)])
        + password_bytes
    )
    try:
        control.sendall(request)
        auth_version, status = receive_exact(control, 2)
    except socket.timeout as error:
        raise CheckError(
            "authentication",
            "timed out while waiting for the username/password authentication response; "
            "no UDP test was performed",
            timeout=True,
        ) from error
    except (ConnectionError, OSError) as error:
        raise CheckError(
            "authentication",
            f"username/password authentication did not complete: {error}",
        ) from error
    if auth_version != 0x01:
        raise CheckError(
            "authentication",
            f"unexpected username/password subnegotiation version 0x{auth_version:02x}",
        )
    if status != 0x00:
        raise CheckError("authentication", "the proxy rejected the supplied credentials")
    return "username_password"


def request_udp_association(
    control: socket.socket,
    udp_socket: socket.socket,
) -> tuple[str, int]:
    local_host, local_port = udp_socket.getsockname()[:2]
    address_type, encoded_address = encode_socks_address(local_host)
    request = (
        bytes([0x05, 0x03, 0x00, address_type])
        + encoded_address
        + struct.pack("!H", local_port)
    )
    control.sendall(request)

    version, reply, reserved, address_type = receive_exact(control, 4)
    if version != 0x05:
        raise CheckError("udp_associate", f"unexpected SOCKS version 0x{version:02x}")
    if reserved != 0x00:
        raise CheckError("udp_associate", "the UDP ASSOCIATE reply has a nonzero reserved field")
    if reply != 0x00:
        meaning = SOCKS_REPLY.get(reply, "unassigned reply code")
        raise CheckError(
            "udp_associate",
            f"the proxy rejected UDP ASSOCIATE: 0x{reply:02x} ({meaning})",
        )

    relay_host = receive_socks_address(control, address_type)
    relay_port = struct.unpack("!H", receive_exact(control, 2))[0]
    if relay_port == 0:
        raise CheckError("udp_associate", "the proxy returned UDP relay port 0")

    try:
        relay_address = ipaddress.ip_address(relay_host)
    except ValueError:
        relay_address = None

    if relay_address is not None and relay_address.is_unspecified:
        relay_host = control.getpeername()[0]

    return relay_host, relay_port


def resolve_udp_endpoint(
    host: str,
    port: int,
    family: socket.AddressFamily,
) -> tuple[tuple, set[tuple[str, int]]]:
    records = socket.getaddrinfo(host, port, family, socket.SOCK_DGRAM)
    if not records:
        raise OSError("the UDP relay address did not resolve")

    endpoint = records[0][4]
    accepted = {
        (str(ipaddress.ip_address(record[4][0])), record[4][1])
        for record in records
    }
    return endpoint, accepted


def encode_dns_name(name: str) -> bytes:
    normalized = name.rstrip(".")
    if not normalized:
        raise ValueError("the DNS name cannot be empty")

    labels = normalized.encode("idna").split(b".")
    encoded = bytearray()
    for label in labels:
        if not 1 <= len(label) <= 63:
            raise ValueError("each DNS label must contain 1 to 63 bytes")
        encoded.append(len(label))
        encoded.extend(label)
    encoded.append(0)
    if len(encoded) > 255:
        raise ValueError("the encoded DNS name exceeds 255 bytes")
    return bytes(encoded)


def build_dns_query(name: str) -> tuple[int, bytes]:
    transaction_id = secrets.randbelow(65536)
    header = struct.pack("!HHHHHH", transaction_id, 0x0100, 1, 0, 0, 0)
    question = encode_dns_name(name) + struct.pack("!HH", 1, 1)
    return transaction_id, header + question


def read_dns_name(message: bytes, offset: int) -> tuple[str, int]:
    labels: list[str] = []
    cursor = offset
    next_offset: int | None = None
    seen_pointers: set[int] = set()

    for _ in range(128):
        if cursor >= len(message):
            raise ValueError("truncated DNS name")
        length = message[cursor]

        if length & 0xC0 == 0xC0:
            if cursor + 1 >= len(message):
                raise ValueError("truncated DNS compression pointer")
            pointer = ((length & 0x3F) << 8) | message[cursor + 1]
            if pointer >= len(message) or pointer in seen_pointers:
                raise ValueError("invalid DNS compression pointer")
            seen_pointers.add(pointer)
            if next_offset is None:
                next_offset = cursor + 2
            cursor = pointer
            continue

        if length & 0xC0:
            raise ValueError("unsupported DNS label encoding")

        cursor += 1
        if length == 0:
            return ".".join(labels), next_offset if next_offset is not None else cursor

        end = cursor + length
        if end > len(message):
            raise ValueError("truncated DNS label")
        labels.append(message[cursor:end].decode("idna"))
        cursor = end

    raise ValueError("DNS name exceeded the parser's pointer limit")


def normalize_dns_name(name: str) -> str:
    return name.rstrip(".").lower()


def parse_dns_records(
    message: bytes,
    offset: int,
    count: int,
    section: str,
) -> tuple[list[dict], int]:
    records: list[dict] = []
    for index in range(count):
        try:
            owner, offset = read_dns_name(message, offset)
        except ValueError as error:
            raise ValueError(
                f"{section} record {index + 1} of {count} has an invalid owner name: "
                f"{error}"
            ) from error
        if offset + 10 > len(message):
            raise ValueError(
                f"{section} record {index + 1} of {count} has a truncated header"
            )

        record_type, record_class, ttl, data_length = struct.unpack(
            "!HHIH", message[offset : offset + 10]
        )
        offset += 10
        data_offset = offset
        data_end = data_offset + data_length
        if data_end > len(message):
            raise ValueError(
                f"{section} record {index + 1} of {count} has truncated RDATA"
            )

        records.append(
            {
                "owner": normalize_dns_name(owner),
                "type": record_type,
                "class": record_class,
                "ttl": ttl,
                "data_length": data_length,
                "data_offset": data_offset,
                "data_end": data_end,
            }
        )
        offset = data_end
    return records, offset


def validate_dns_response(
    response: bytes,
    expected_id: int,
    expected_name: str,
) -> dict:
    if len(response) < 12:
        raise ValueError("the DNS response is shorter than its 12-byte header")

    transaction_id, flags, questions, answers, authorities, additionals = struct.unpack(
        "!HHHHHH", response[:12]
    )
    if transaction_id != expected_id:
        raise ValueError("the DNS transaction ID does not match the query")
    if flags & 0x8000 == 0:
        raise ValueError("the DNS packet is not marked as a response")
    if (flags >> 11) & 0x0F:
        raise ValueError("the DNS response uses a nonstandard opcode")
    if flags & 0x0200:
        raise ValueError("the DNS response is truncated")

    response_code = flags & 0x000F
    if response_code != 0:
        raise ValueError(f"the DNS response code is {response_code}, not NOERROR")
    if questions != 1:
        raise ValueError(f"expected one DNS question, received {questions}")

    offset = 12
    question_name, offset = read_dns_name(response, offset)
    if offset + 4 > len(response):
        raise ValueError("the DNS question is truncated")
    question_type, question_class = struct.unpack("!HH", response[offset : offset + 4])
    offset += 4

    expected_owner = normalize_dns_name(expected_name)
    if normalize_dns_name(question_name) != expected_owner:
        raise ValueError("the DNS question name does not match the requested name")
    if (question_type, question_class) != (1, 1):
        raise ValueError("the DNS question is not an IN A query")

    answer_records, offset = parse_dns_records(response, offset, answers, "answer")
    _, offset = parse_dns_records(response, offset, authorities, "authority")
    _, offset = parse_dns_records(response, offset, additionals, "additional")
    if offset != len(response):
        raise ValueError(
            f"the DNS response contains {len(response) - offset} trailing byte(s) "
            "after its declared sections"
        )

    cname_edges: list[tuple[str, str]] = []
    address_records: list[tuple[str, str]] = []
    for record in answer_records:
        if record["class"] != 1:
            continue

        if record["type"] == 5:
            target, cname_end = read_dns_name(response, record["data_offset"])
            if cname_end != record["data_end"]:
                raise ValueError("a CNAME answer contains invalid trailing RDATA")
            cname_edges.append((record["owner"], normalize_dns_name(target)))
        elif record["type"] == 1:
            if record["data_length"] != 4:
                raise ValueError("an IN A answer does not contain a 4-byte IPv4 address")
            address_records.append(
                (
                    record["owner"],
                    socket.inet_ntop(
                        socket.AF_INET,
                        response[record["data_offset"] : record["data_end"]],
                    ),
                )
            )

    validated_names = [expected_owner]
    validated_set = {expected_owner}
    for _ in range(len(cname_edges) + 1):
        changed = False
        for owner, target in cname_edges:
            if owner in validated_set and target not in validated_set:
                validated_set.add(target)
                validated_names.append(target)
                changed = True
        if not changed:
            break

    ipv4_answers = [
        address for owner, address in address_records if owner in validated_set
    ]

    if not ipv4_answers:
        raise ValueError(
            "the DNS response contains no IPv4 A answer owned by the requested "
            "name or a validated CNAME chain"
        )

    return {
        "transaction_id_matched": True,
        "response_code": response_code,
        "declared_records": {
            "answers": answers,
            "authorities": authorities,
            "additionals": additionals,
        },
        "validated_name_chain": validated_names,
        "ipv4_answers": ipv4_answers,
    }


def parse_socks_udp_response(packet: bytes) -> tuple[str, int, bytes]:
    if len(packet) < 4:
        raise ValueError("the SOCKS5 UDP response is shorter than its header")
    if packet[:2] != b"\x00\x00":
        raise ValueError("the SOCKS5 UDP response has a nonzero reserved field")

    fragment = packet[2]
    if fragment != 0:
        raise ValueError(f"fragmented SOCKS5 UDP response is unsupported (FRAG={fragment})")

    remote_host, offset = decode_socks_address(packet, 4, packet[3])
    if offset + 2 > len(packet):
        raise ValueError("the SOCKS5 UDP response is missing its remote port")
    remote_port = struct.unpack("!H", packet[offset : offset + 2])[0]
    payload = packet[offset + 2 :]
    if not payload:
        raise ValueError("the SOCKS5 UDP response contains no payload")
    return remote_host, remote_port, payload


def normalized_ip(value: str) -> str:
    return str(ipaddress.ip_address(value))


def run_check(args: argparse.Namespace) -> dict:
    username = os.getenv("SOCKS5_USERNAME")
    password = os.getenv("SOCKS5_PASSWORD")
    resolver = normalized_ip(args.resolver)
    started = time.monotonic()
    control: socket.socket | None = None
    udp_socket: socket.socket | None = None
    stage = "configuration"

    try:
        stage = "tcp_connect"
        control = socket.create_connection(
            (args.proxy_host, args.proxy_port), timeout=args.timeout
        )
        control.settimeout(args.timeout)

        stage = "method_negotiation"
        authentication = negotiate_authentication(control, username, password)

        local_host = control.getsockname()[0]
        udp_socket = socket.socket(control.family, socket.SOCK_DGRAM)
        udp_socket.settimeout(args.timeout)
        if control.family == socket.AF_INET6:
            udp_socket.bind((local_host, 0, 0, 0))
        else:
            udp_socket.bind((local_host, 0))

        stage = "udp_associate"
        relay_host, relay_port = request_udp_association(control, udp_socket)
        relay_endpoint, accepted_relay_sources = resolve_udp_endpoint(
            relay_host, relay_port, control.family
        )

        transaction_id, dns_query = build_dns_query(args.name)
        resolver_type, resolver_address = encode_socks_address(resolver)
        udp_request = (
            b"\x00\x00\x00"
            + bytes([resolver_type])
            + resolver_address
            + struct.pack("!H", 53)
            + dns_query
        )

        stage = "udp_relay"
        udp_socket.sendto(udp_request, relay_endpoint)
        packet, sender = udp_socket.recvfrom(65535)
        sender_key = (normalized_ip(sender[0]), sender[1])
        if sender_key not in accepted_relay_sources:
            raise CheckError(
                stage,
                f"received a datagram from {sender_key[0]}:{sender_key[1]}, "
                "not the negotiated UDP relay",
            )

        stage = "socks_udp_response"
        remote_host, remote_port, dns_response = parse_socks_udp_response(packet)
        if normalized_ip(remote_host) != resolver or remote_port != 53:
            raise CheckError(
                stage,
                f"the SOCKS5 UDP response identifies {remote_host}:{remote_port}, "
                f"not {resolver}:53",
            )

        stage = "dns_response"
        dns_result = validate_dns_response(dns_response, transaction_id, args.name)

        return {
            "passed": True,
            "proxy": {
                "host": args.proxy_host,
                "port": args.proxy_port,
                "authentication": authentication,
            },
            "udp_association": {
                "accepted": True,
                "relay_host": relay_host,
                "relay_port": relay_port,
            },
            "probe": {
                "resolver": f"{resolver}:53",
                "name": args.name,
                "socks_response_source": f"{remote_host}:{remote_port}",
                **dns_result,
            },
            "elapsed_ms": round((time.monotonic() - started) * 1000, 2),
        }
    except socket.timeout as error:
        raise CheckError(
            stage,
            "the operation timed out; this is inconclusive because routing, firewall "
            "rules, destination policy, congestion, or packet loss can also cause silence",
            timeout=True,
        ) from error
    except CheckError:
        raise
    except (ConnectionError, OSError, UnicodeError, ValueError) as error:
        raise CheckError(stage, str(error)) from error
    finally:
        if udp_socket is not None:
            udp_socket.close()
        if control is not None:
            control.close()


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Validate SOCKS5 UDP ASSOCIATE with a DNS A query."
    )
    parser.add_argument("--proxy-host", required=True)
    parser.add_argument("--proxy-port", required=True, type=int)
    parser.add_argument("--resolver", default="8.8.8.8")
    parser.add_argument("--name", default="example.com")
    parser.add_argument("--timeout", default=5.0, type=float)
    args = parser.parse_args()

    if not 1 <= args.proxy_port <= 65535:
        parser.error("--proxy-port must be between 1 and 65535")
    if not 0.1 <= args.timeout <= 60:
        parser.error("--timeout must be between 0.1 and 60 seconds")
    try:
        normalized_ip(args.resolver)
        encode_dns_name(args.name)
    except ValueError as error:
        parser.error(str(error))
    return args


def main() -> int:
    args = parse_args()
    try:
        result = run_check(args)
    except CheckError as error:
        result = {
            "passed": False,
            "stage": error.stage,
            "error": error.message,
            "timeout_is_inconclusive": error.timeout,
        }
        print(json.dumps(result, indent=2, sort_keys=True))
        return 1

    print(json.dumps(result, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

The code intentionally keeps the TCP control socket open until after DNS validation. It also reports only the proxy host, port, and authentication method. The username and password are read from the environment but never included in the result object.

## Run the Test

Run the default DNS probe:

```bash
python3 socks5_udp_check.py \
  --proxy-host proxy.example.test \
  --proxy-port 1080
```

To use a different approved resolver or DNS name:

```bash
python3 socks5_udp_check.py \
  --proxy-host proxy.example.test \
  --proxy-port 1080 \
  --resolver 8.8.4.4 \
  --name example.com \
  --timeout 8
```

Do not add credentials as command-line flags. Command arguments may be visible to other processes, recorded by shell history, or captured in support output.

## How to Read a Passing Result

A successful result looks like this example:

```json
{
  "elapsed_ms": 184.27,
  "passed": true,
  "probe": {
    "declared_records": {
      "additionals": 0,
      "answers": 1,
      "authorities": 0
    },
    "ipv4_answers": [
      "93.184.216.34"
    ],
    "name": "example.com",
    "resolver": "8.8.8.8:53",
    "response_code": 0,
    "socks_response_source": "8.8.8.8:53",
    "transaction_id_matched": true,
    "validated_name_chain": [
      "example.com"
    ]
  },
  "proxy": {
    "authentication": "username_password",
    "host": "proxy.example.test",
    "port": 1080
  },
  "udp_association": {
    "accepted": true,
    "relay_host": "192.0.2.20",
    "relay_port": 40123
  }
}
```

The example values are illustrative. A pass establishes all of the following for that one probe:

1. The TCP SOCKS5 endpoint was reachable.
2. The selected authentication method succeeded.
3. The proxy accepted UDP ASSOCIATE.
4. The reply arrived from the negotiated UDP relay.
5. The SOCKS5 UDP reserved field was zero and FRAG was zero.
6. The embedded source was the requested resolver on UDP port 53.
7. The DNS transaction ID matched the query.
8. The packet was a non-truncated standard DNS response with NOERROR.
9. Every record declared in the answer, authority, and additional counts was structurally present, with no undeclared trailing bytes.
10. The response repeated the expected question and contained an IPv4 A answer owned by that name or a validated CNAME chain rooted at it.

This is stronger than checking for “some bytes,” but it is still scoped evidence. It does not establish access to other resolvers, arbitrary UDP ports, QUIC, games, voice applications, or every network path.

## How to Read a Failure

The stage field identifies the last operation attempted:

| Failure stage | Likely area to inspect | Does it prove UDP is unsupported? |
|---|---|---|
| `configuration` | Missing credential pair, invalid port, invalid resolver, or invalid DNS name | No |
| `tcp_connect` | Proxy hostname, TCP port, local route, allowlist, or firewall | No |
| `method_negotiation` | Wrong endpoint, unsupported authentication method, or non-SOCKS service | No |
| `authentication` | Username, password, account state, or access policy | No |
| `udp_associate` | SOCKS reply code, proxy policy, command support, or address-type support | Sometimes; inspect the explicit reply code |
| `udp_relay` | Local UDP route, relay reachability, client source restriction, destination policy, congestion, or packet loss | No; a timeout is inconclusive |
| `socks_udp_response` | Malformed relay envelope, fragmentation, unexpected relay source, or wrong embedded source | It proves this response was not accepted as a valid result |
| `dns_response` | Mismatched transaction, bad flags, DNS error, incomplete declared section, wrong question, unrelated A-record owner, broken CNAME chain, or missing A answer | No; UDP transport may have worked while the payload failed validation |

For example, a silent test returns an error similar to:

```json
{
  "error": "the operation timed out; this is inconclusive because routing, firewall rules, destination policy, congestion, or packet loss can also cause silence",
  "passed": false,
  "stage": "udp_relay",
  "timeout_is_inconclusive": true
}
```

That language is deliberate. RFC 1928 allows a UDP relay to silently drop a datagram it cannot or will not relay. UDP itself also has no delivery acknowledgement. Silence therefore identifies a symptom, not its unique cause.

## SOCKS5 UDP ASSOCIATE Reply Codes

When stage is udp_associate, the checker includes the proxy's REP code and its standard meaning.

| Code | RFC 1928 meaning | Practical next check |
|---|---|---|
| `0x01` | General SOCKS server failure | Review proxy logs or ask the provider which condition failed |
| `0x02` | Connection not allowed by ruleset | Confirm UDP use and the selected destination are permitted |
| `0x03` | Network unreachable | Check the proxy's route to the requested network |
| `0x04` | Host unreachable | Verify the resolver address and upstream reachability |
| `0x05` | Connection refused | Confirm the endpoint and destination service |
| `0x06` | TTL expired | Investigate the upstream network path |
| `0x07` | Command not supported | The endpoint rejected `UDP ASSOCIATE`; confirm that UDP-over-SOCKS5 is available on that product or port |
| `0x08` | Address type not supported | Try a supported IPv4, IPv6, or domain address type as appropriate |

A 0x00 success reply proves only that the association was accepted. The relay still needs to return a valid application response before the end-to-end test passes.

## Troubleshoot an Inconclusive Timeout

Use a controlled sequence rather than immediately concluding that the proxy lacks UDP support.

### 1. Confirm the control endpoint

Verify that the hostname, port, authentication method, account allowlist, and product are correct. A SOCKS5 endpoint and an HTTP proxy endpoint are not interchangeable. Ordinary HTTP proxy support does not imply arbitrary UDP relay support.

### 2. Inspect the last successful stage

If the test never reaches udp_associate, solve the TCP or authentication issue first. If the proxy returns 0x07, it explicitly rejected the command. If the association succeeds but the relay is silent, more than one explanation remains.

### 3. Check the negotiated relay address

The UDP relay address may differ from the TCP proxy address. Ensure the client can send UDP to the returned address and port. Check outbound firewall rules, security groups, container networking, Kubernetes network policies, NAT behavior, and VPN routes.

The relay can also associate packets with the source address used by the client. Running the TCP control connection and UDP socket from different hosts or network paths can cause packets to be dropped.

### 4. Run a direct control test from the same machine

Test whether the selected resolver is reachable directly from the same environment, without the proxy, if your policy permits it. A failed direct control suggests the destination or local network—not the SOCKS5 relay—is the first issue to solve.

Do not treat a successful direct DNS query as proof that the proxy path must work. It only removes one variable.

### 5. Try one second approved resolver

If policy permits, run one bounded retry with another known resolver, such as 8.8.4.4. A destination-specific block can otherwise look like general UDP failure. Avoid an unbounded retry loop because it hides the failure rate and generates unnecessary traffic.

### 6. Check proxy-side evidence

If you operate the SOCKS5 server, inspect its logs and packet counters. If you use a managed service, give support the timestamp, proxy host and port, returned REP code, relay address, resolver, and failure stage. Do not send the password or an unredacted command history.

### 7. Capture packets only in an approved environment

A packet capture can show whether the UDP request left the client and whether a reply reached it. Protect the capture as sensitive operational data: authentication traffic, internal addresses, DNS queries, and other application data may be present.

## Why DNS Is a Better First Probe Than a Browser or VoIP App

DNS gives the checker a compact request and a structured response with fields that can be independently validated. The [DNS message format in RFC 1035](https://www.rfc-editor.org/rfc/rfc1035.html) provides a transaction ID, response flag, operation code, return code, question section, and typed answer records.

By contrast, a browser may disable or reroute QUIC, fall back from HTTP/3 to TCP-based HTTP/2, use encrypted DNS through another path, or apply its own proxy rules. A voice or gaming application can fail because of authentication, media negotiation, NAT, codecs, application servers, or firewall policy. Those are useful workload tests after the transport path is understood, but weak first diagnostics for SOCKS5 UDP.

An NTP request is also small, but a raw timestamp response provides fewer query-specific validation fields than DNS. Receiving one packet is not enough unless the client verifies it belongs to the request it sent.

## When to Use tun2socks

Use tun2socks when the application cannot speak SOCKS5 UDP itself and you need to route operating-system traffic through a SOCKS proxy. Test the proxy directly first. That separates proxy capability from TUN-device, route, DNS, and application configuration.

A typical engine command resembles:

```bash
tun2socks --device tun://tun0 --proxy socks5://proxy.example.test:1080
```

That command alone does not complete system routing. Creating a TUN interface and changing routes normally requires elevated privileges. A bad route can disconnect the machine or send the proxy's own traffic back into the tunnel, creating a loop. Use the project's current [tun2socks examples](https://github.com/xjasonlyu/tun2socks/wiki/Examples), preserve an out-of-band recovery path, and explicitly exclude the SOCKS5 server from the tunnel route.

Do not paste credentials into a shared terminal recording or a repository. Use the tool's supported secret-handling method for your environment.

## Does This Test QUIC or HTTP/3?

No. The checker proves one DNS-over-UDP exchange through one SOCKS5 relay. QUIC and HTTP/3 also use UDP, but browser support, proxy configuration, destination policy, TLS, and connection migration introduce different variables.

If your actual requirement is HTTP/3, first pass this low-level relay test, then run a separate application-level test with a client that explicitly documents how it carries QUIC through SOCKS5. Confirm the traffic path with client diagnostics or approved network evidence. Do not infer QUIC support merely because a website loads: the browser may have fallen back to TCP.

## Testing UDP With Proxidize

UDP support is specific to the selected product, version, endpoint, protocol, and configuration. The current [Proxidize Gen 2 release notes](https://help.proxidize.com/en/proxidize-gen-2-changelogs-release-notes) state that version 0.6.13 added a Settings-page option for enabling UDP through SOCKS5 proxies. That product-specific note does not establish support on every residential or managed mobile endpoint, and it does not document that every UDP destination or port is permitted.

The default checker requires outbound UDP port 53 to the resolver selected with --resolver. Before running it, confirm that UDP-over-SOCKS5 is enabled on the exact Gen 2 endpoint and that its destination policy permits the resolver and port. If UDP/53 is not permitted, this DNS probe is not suitable; use a provider-approved UDP destination and a validator designed for that application protocol. An HTTP endpoint cannot carry arbitrary UDP simply because another endpoint offers SOCKS5.

Proxidize provides the network connection and proxy controls. Your application still owns protocol behavior, timeouts, validation, retry policy, evidence handling, and compliance with the destination's rules and applicable law.

## Common Testing Mistakes

### Accepting an unrelated response

Validate the negotiated relay, SOCKS5 envelope, complete DNS sections, and answer owner. An unrelated A record does not satisfy the query unless it is reached through a validated CNAME chain rooted at the requested name.

### Testing the wrong endpoint or closing it early

Use the documented SOCKS5 endpoint, not an HTTP proxy port, and keep the TCP control connection open until validation finishes. The control connection defines the lifetime of the UDP association.

### Calling every timeout “no UDP support”

Silence can result from local routing, firewall policy, source restrictions, destination policy, congestion, or packet loss. Report it as inconclusive and isolate each layer.

### Putting credentials in the output

Test reports need a host, port, timestamp, failure stage, and sanitized configuration—not a username or password. Redact secrets from logs, tickets, screenshots, packet captures, and repositories.

## Validation Notes for This Guide

The checker was syntax-validated with Python 3.11 and exercised against a local mock SOCKS5 server on September 22, 2026. Thirteen automated tests covered:

- A valid unauthenticated UDP association and DNS answer.
- A valid username/password flow with an assertion that the serialized result contains neither credential.
- An authentication timeout attributed to the authentication stage.
- A rejected UDP ASSOCIATE command.
- A nonzero reserved field in the SOCKS5 UDP reply.
- A fragmented reply.
- A mismatched DNS transaction ID.
- An unrelated A-record owner being rejected.
- A valid CNAME chain leading to an accepted A record.
- A declared but missing additional record being rejected.
- A silent relay timeout reported as inconclusive.
- Domain-address parsing.
- IPv6-address encoding and parsing.

These are protocol and control-flow tests, not a production proxy benchmark. No live provider endpoint was used, and the results do not measure latency, success rate, destination coverage, or support across products. Run the checker against your authorized endpoint and workload before relying on it operationally.

## Final Recommendation

Start with the direct checker, preserve its failure stage, and investigate timeouts rather than converting silence into a definitive verdict. Move to tun2socks or an application-level test only after the controlled probe has separated proxy behavior from system routing and application configuration.

## Frequently Asked Questions

### Does SOCKS5 always support UDP?

No. SOCKS5 defines the UDP ASSOCIATE command, but a particular server, product, account, or endpoint may not implement or permit it. Confirm the exact endpoint and test it.

### What proves that SOCKS5 UDP is working?

A strong test shows that the proxy accepted UDP ASSOCIATE, returned a usable relay, sent back a valid SOCKS5 UDP envelope from that relay, and carried an application response that matches the original request. This guide requires a complete DNS response with an A record owned by the queried name or a validated CNAME chain rooted at it.

### Does an accepted UDP ASSOCIATE request prove end-to-end UDP works?

No. It proves that the server accepted the association request. You still need to send an encapsulated UDP datagram and validate the application response returned through the negotiated relay.

### Does a timeout mean the proxy does not support UDP?

No. A timeout is inconclusive because local routing, firewall rules, relay reachability, source restrictions, destination policy, congestion, or packet loss can all produce silence. An explicit 0x07 reply is stronger evidence that the endpoint does not support the requested command.

### Why must the TCP control connection stay open?

RFC 1928 ties the UDP association to the TCP connection that requested it. Closing that connection ends the association, so the checker keeps it open until the UDP response has been validated.

### Can cURL test SOCKS5 UDP support?

cURL is useful for TCP-based protocols through SOCKS5, but it is not a general arbitrary-UDP UDP ASSOCIATE checker. Use a purpose-built client such as the Python script in this guide for a controlled DNS-over-UDP probe.

### Can a browser prove that UDP or QUIC works through the proxy?

Not reliably by itself. A browser can fall back from HTTP/3 to TCP-based HTTP/2, use a different DNS path, or apply its own proxy rules. Use the direct checker first, then an application-specific test with diagnostics that confirm the actual route and protocol.

### What is tun2socks used for?

tun2socks routes traffic from a virtual network interface through a SOCKS proxy. It is helpful for applications without native SOCKS support, but it adds operating-system routing and TUN configuration that can obscure a basic proxy test.

### Are SOCKS5 username and password credentials encrypted?

Not by the RFC 1929 username/password subnegotiation itself. Use a trusted network path or an additional protected transport suitable for your environment, and never expose credentials in code, command arguments, logs, screenshots, or test reports.

### Why might the checker receive a packet and still fail?

The packet may come from the wrong sender, contain an invalid SOCKS5 UDP header, identify the wrong destination, carry a mismatched DNS transaction, report a DNS error, or contain no acceptable answer. Receiving bytes is necessary but not sufficient for a valid result.
