Connection refused errno 111: reset or silence, and which retry

Dark cover headed 'Connection refused': errno 111, a reset that answers in 7.68 microseconds, a 2-deep accept queue that answers nothing, and 25 passing tests

Updated December 3, 2026 · every figure below was measured on the host described in Section 1 unless its table marks it as documented, and a table that counts runs says how many it used.

On one Linux host, one process holds a port and a second process dials it. When the second dials an address the first is not listening on – another loopback address, 127.0.0.2 against a listener on 127.0.0.1, or a unix socket path whose process is gone – the connect fails in microseconds with ConnectionRefusedError: [Errno 111] Connection refused. A reset came back, so the packet reached a stack that answered; the only thing missing was a socket in the listening state at that address. That claim is what this page tests, one socket state at a time, and every figure below comes from a socket the page created.

The same errno is also the wrong thing to look for. A listener whose accept queue is full, on a host that does not reset it, answers nothing at all: the client waits out its own timeout, raises an exception with no errno, and an operator reads that as a network problem. A refusal is one round trip and an answer; silence is the absence of one, and the two need opposite responses.

Across a network or a container bridge the same symptom can come from a middlebox rather than a listener: a firewall that rejects with a reset, a port forward to nothing, a namespace where 127.0.0.1 belongs to the container and not the host. Those change who answers, not what the number means, and the check that separates them is the curl pair in Section 6. This page measures the socket states it can build on one host.

Four conditions could not be measured here and are marked documented wherever they appear: the kernel switch that resets a full queue, a firewall’s drop or reject (this process has no root to write a ruleset), the IPv6 dual-stack rule, and the errno numbers of other operating systems. Table 2 records the 2-vCPU guest and the limits that decide what a refusal can look like.

TL;DR — errno 111 is ECONNREFUSED: a SYN answered with a reset, which proves the host was reachable and that address and port had no listener. A listener on another address, a socket bound but never listening and a stale unix socket file refuse the same way. Retry a refusal inside a deadline while a peer is starting; treat a timeout as a question about the path.

Fix It First: Ten Changes, Matched to What You Saw

The first column is the evidence in front of you, the second the cheapest check that separates this cause from the others, and the third the change that makes the evidence stop. Nine of the ten rows were produced by one of the measurements below, on the host in Table 2; the firewall row is the exception, and it says so.

What you seeCheapest checkChange that ends it
ConnectionRefusedError while the service reports healthycompare the listener’s bind address with the address being dialled (Section 3)bind the address the client uses, or dial the one the listener holds
Refused on one loopback address and fine on the nextprint the listener’s bind addressa wildcard listener answers every local address; a specific one answers only its own
A connect to 0.0.0.0 that reaches the local host instead of a peerdial 0.0.0.0 and 127.0.0.1 on that port (Section 3)fill in the address the peer actually holds; as a destination, 0.0.0.0 is loopback
The port is held by a process and still refuseslook for the listening state, not for the descriptora socket that was bound but never called listen accepts nothing
A unix socket path exists and connects are refusedcheck whether a process is listening on the pathremove the stale file before binding; the file is not a liveness check
Connects hang under load instead of failingread the listener’s accept queue while the clients pile up (Section 4)accept faster or raise the backlog; a full queue drops SYNs and turns a refusal into a timeout
A service port that times out while a closed port is refuseddial a port on the same host that nothing could be listening onsomething between you and the port is dropping the packets: the silence measured here came from a full accept queue (Section 4), and a firewall that drops or rejects is documented, not measured
A retry loop that never connectslog the reason at every attempt, not only at the last oneretry only a refusal, inside a deadline, with a doubling wait
A hostname that fails while its address worksresolve the name and log every address it returned, in orderdial every address instead of the first, and let a refusal fall through to the next
A refusal that came a moment before the service was readyrecord the time of the first refusal and the time the port openedthe deploy is a race, not an outage: retry to a deadline and report the attempts
Table 1: Ten symptoms, the check that identifies each, and the change that ends it.

1. What the Number Measures, and on What Host

errno 111 is ECONNREFUSED, and on this host os.strerror renders it as “Connection refused”. It is produced by a reset that answers a SYN, which the TCP specification describes as the response to a segment that matches no connection (RFC 9293, section 3.10.7.1). A reset is a packet the peer’s stack sent, so the path worked in both directions, the host was up, and the decision to refuse was made remotely.

Each arm below builds one socket state, connects once, and records what the caller would catch: an errno, an exception class, or success. Rows that answer with an errno ran once, because an errno does not move between runs; the timing rows in Section 6 ran five times.

ConditionValue on this host
Kernel6.12.118-guest-1.2
Python3.12.16, 64-bit
Machine and CPUsx86_64, 2 vCPU
Shell/bin/dash; /bin/bash 5.2.37(1)-release
curl8.14.1
User id1000: not root, so kernel switches are readable and not writable
Interface address10.100.0.2; loopback 127.0.0.1, 127.0.0.2, 127.0.0.53, 127.0.0.254 all bindable
IPv6 loopbacknot available: ::1 answers “Address family not supported by protocol”
/etc/hostsabsent, so localhost does not resolve: “Name or service not known”
Name with several addressestechbobby.com resolved to 4 addresses across 2 families
net.core.somaxconn4,096
tcp_max_syn_backlog128
tcp_abort_on_overflow0
tcp_syncookies1
tcp_syn_retries6
Table 2: The host every figure in this page was measured on, and the limits that decide what a refused connect can look like.

Three limits in that table shape what follows. The overflow switch reads 0, and writing it needs a privilege this process lacks: the file answers “Permission denied”. So Section 4 measures the silence this host produces, and the reset the other setting would send is documented. The guest has no IPv6 loopback, so the dual-stack rule is described from the specification and marked wherever a table meets it. The missing hosts file is the third: localhost is a name, and here it never reaches TCP at all. One more case is missing because this process is not root: a ruleset that drops or rejects cannot be written, so the only silence measured on this page is the accept queue’s (Section 4), and Table 1 marks its firewall row as documented.

Why not measure the interface address?

A connect to the guest’s own 10.100.0.2 did not complete: with the listener bound to the wildcard, the same port answered on 127.0.0.1 and stayed silent for 2,002 ms on the interface address. That is this sandbox’s network, not Linux, so every measured row uses loopback and the one row that shows the interface address is labelled with what happened.

2. Three Answers, One Failed Connect

A failed connect is one of three things, and only the first of them is errno 111. The peer’s stack answers with a reset, and the caller sees ECONNREFUSED. Nothing answers at all, and the caller’s own timeout ends the attempt with no errno. Or the local kernel refuses before it sends anything, because the address has no route. The three point at three owners: the service’s configuration, the path, and the client’s own address.

  • A reset. The host is up, the packet arrived, and its TCP stack had no listening socket for that address and port. The refusal is an answer, it arrives in one round trip, and it means the port is closed at the address that was dialled.
  • Silence. No answer arrives, and the attempt ends when the client’s timeout expires. A firewall that drops, a host that is down and a listener whose accept queue is full all look like this from the client, and silence proves nothing about the service.
  • A local refusal. The kernel cannot route the packet: ENETUNREACH (101) when the network is unreachable and EHOSTUNREACH (113) when the host is, or a resolver failure before either. No amount of retrying the same address changes these.

The measured evidence for a refusal is unremarkable, which is what a good diagnosis looks like: a port with no socket at all, a socket that was bound and never listened, a UDP socket holding the number against a TCP client, and a service that had stopped a moment earlier all returned errno 111 at the first attempt. The variation lives in the address and in the queue, the next two sections.

The second kind needs a clock the client owns, and that is where most of the confusion in production tickets starts. Nothing in the kernel tells a client that a firewall dropped its SYN; the client learns only that its own timer expired. The timeout value is a statement about the caller’s patience, not the network’s statement about the service.

Why does the same program sometimes print 111 and sometimes time out?

Because the answers come from different places. A refusal is produced by the remote stack in response to the SYN, so it is as fast as the round trip; a timeout is produced locally when the deadline passes. On the loopback the gap is stark: a refusal returned in microseconds, and the same client against a full accept queue waited the full 2,002 ms it had allowed.

3. The Address the Listener Is On

A listening socket is bound to an address as well as a port, and it answers only for that address. A service that bound 127.0.0.1 and a client that dials the host’s address meet that rule: the remote stack answers honestly that nothing is listening there. The matrix below changes one thing at a time, which address the listener holds and which address the client dials.

Listener bound toClient dialsAnswerWhat it means
nothing127.0.0.1111 ECONNREFUSEDthe port is closed
bound, never listened127.0.0.1111 ECONNREFUSEDa descriptor is not a listener
127.0.0.1127.0.0.2111 ECONNREFUSEDanother local address is another address
0.0.0.0127.0.0.1connectedthe wildcard answers loopback
0.0.0.0127.0.0.2connectedand every other local address
0.0.0.00.0.0.0connected, peer 127.0.0.1as a destination the wildcard means loopback
0.0.0.010.100.0.2TimeoutErrora sandbox property, not a listener property
10.100.0.2127.0.0.1111 ECONNREFUSEDthe specific address does not cover loopback
UDP socket127.0.0.1111 ECONNREFUSEDthe port is taken, the TCP port is not
service stopped127.0.0.1111 ECONNREFUSEDa closed port does not linger
unix, no filepath2 ENOENTthe name does not exist at all
unix, stale filepath111 ECONNREFUSEDthe file exists, the listener does not
Table 3: Twelve placements of one port and the answer each produced. Every row ran once; an answer of this kind does not move between runs.

Two rows carry the rule. The wildcard listener answered on 127.0.0.1 and on 127.0.0.2 alike, because a socket bound to the wildcard address is bound to every local address, while the specific listener answered on neither of the others. A client that dials 0.0.0.0 reaches loopback, because the kernel maps the wildcard destination to the local host.

The unix rows explain a failure that looks like a network problem and is not one. A missing path fails with ENOENT (2), an error about a name; a path that exists with no listener behind it fails with 111, the same refusal a closed TCP port gives, which unix(7) lists for exactly that case. The stale file is the classic deploy artifact: the process died, the file stayed, and every client now gets a refusal that reads like a running service saying no.

What the dual-stack case does, and why it is only described here

A hostname commonly resolves to an IPv6 address and an IPv4 address, and a client that tries them in order can be refused by one and served by the other. The rule for a listener is RFC 3493: a socket bound to the IPv6 wildcard accepts IPv4 connections only when IPV6_V6ONLY is off, and a socket bound to ::1 never accepts an IPv4 connection. This guest has no IPv6 loopback (“Address family not supported by protocol”), so this paragraph is documentation rather than measurement. On the host that resolved techbobby.com to 4 addresses in 2 families, the resolver’s order is the order a client tries, which is why Section 7 dials every address.

4. The Queue Behind a Busy Listener

A listener that is up and not accepting looks, to a client, like a port with nothing behind it – except that it produces no refusal. The kernel completes handshakes into a queue, and a connection that arrives when the queue is full meets a check in the SYN path before it is answered. The measurement fills the queue without ever calling accept, reads its length from the kernel’s own table, then times one more connect with select, so a handshake that completes is told apart from one that is never answered.

Connections that completedQueue length readWhat happened next
11listen(0) still holds one connection
22listen(1) holds two
1717listen(16) holds seventeen
no answerfullconnect_ex returned 115 and the socket was not writable after 2,002 ms
one accept, then connectedone place freedwritable in 38 µs
Table 4: The accept queue filled without a single accept, and the connect that followed.

The first three rows give the rule: the queue holds one more than the number passed to listen. listen(n) stores n in sk_max_ack_backlog, and sk_acceptq_is_full() compares sk_ack_backlog > sk_max_ack_backlog – a strict >, not >=. While n connections wait the test is false and one more is admitted; once n+1 wait, the next is turned away. The measured fills follow it exactly: listen(0) held 1, listen(1) held 2, listen(16) held 17.

Two points on the handshake decide admission with that test. tcp_conn_request() runs it when a SYN arrives, and a full queue drops the SYN with no answer – the silence the fourth row measures. tcp_v4_syn_recv_sock() runs the test again when the final ACK would create the child socket, for a queue that filled between the two packets. tcp_check_req() tests nothing itself: it is where a child that could not be created lands, and where tcp_abort_on_overflow picks the answer to the ACK – 0 drops it and the client keeps waiting, 1 sends a reset.

The queue length is readable on any host: the listening socket’s rx_queue column in /proc/net/tcp reported the same count the accepts did, which is the figure to watch when a client says the service is up and connects hang.

The fourth row is the silence that check produces. With tcp_abort_on_overflow at 0, connect_ex returned 115 and the descriptor never became writable inside 2,002 ms: the SYN met a full queue and was dropped, so only the client’s own timer ends the attempt. A saturated listener is therefore indistinguishable from a firewall that drops. The other setting turns the later stage into a reset: Documentation/networking/ip-sysctl.txt states that a value of one makes the kernel reset the connection instead of ignoring the ACK. That row is documented, not measured, because this process cannot write the switch.

The fifth row separates capacity from a dead service. One accept freed one place, and the next connect completed in 38 microseconds: nothing was wrong with the port, the address or the path, and the queue was the only thing between the client and a connection. A service whose accept loop is slow, blocked or single-threaded therefore fails in bursts a client experiences as timeouts, and the fix is in the loop or the backlog.

Two kernel settings bound the backlog. A value larger than net.core.somaxconn (4,096 here) is clipped to it, and with syncookies enabled (1 here) the kernel can complete a handshake without keeping a queue entry for the SYN, which is why the accept queue, not the SYN backlog, is the number that matters once a listener is accepting at all. The SYN backlog (128) governs the earlier stage, and tcp_syn_retries (6) governs how long a client spends on an unanswered SYN before the kernel gives up, on the backoff of RFC 6298.

5. Nine Clients, One Refusal, Many Wrappers

Once the kernel has answered with a reset, every Python client on the host has the same errno to work with and a different way of presenting it. The table puts nine clients against one closed loopback port, adds the two inspections a caller usually writes, and records what the caller would catch: the class, the errno where the class carries one, and the chain of wrappers where it does not. except ConnectionRefusedError sees only the first group.

SurfaceWhat the caller catchesWhere the number is
socket.connectConnectionRefusedError, errno 111the class is the errno
socket.connect_exreturns 111the number is the return value
socket.create_connectionConnectionRefusedErrorsame class, after the address loop
urllib.request.urlopenURLError whose reason is a ConnectionRefusedErrorone level down
http.clientConnectionRefusedErrorsame class
requestsConnectionError → MaxRetryError (urllib3) → NewConnectionError (urllib3) → ConnectionRefusedErrorthree levels down, errno 111
httpxConnectError (httpx) → ConnectError (httpcore) → ConnectionRefusedErrortwo levels down, errno 111
asyncio.open_connectionConnectionRefusedError, errno 111the message names the address, not the number
aiohttpClientConnectorError, errno 111a client error, not an OSError
repr of the exceptionConnectionRefusedError(111, 'Connection refused')the number and the message
isinstance checksConnectionError yes, TimeoutError noa refusal is not a timeout
Table 5: Nine clients against one closed port, plus the two checks a caller writes; eleven rows in all. Each ran once; a class name does not move between runs.

Those rows are not eleven different failures. Read the requests row from the inside out and the innermost exception is the same builtin the raw socket raised; the aiohttp row carries errno 111 on a class that inherits from OSError but not from ConnectionError. That is the argument for logging the class, the errno and the chain rather than str(exc): the asyncio string names the address, the requests string names its retry wrapper, and neither contains the number an alert is keyed on.

Is a refusal always instantaneous?

On the loopback it is, because the reset comes back on the same machine; over a network it takes one round trip, still far shorter than a timeout. What makes a refusal fast is that it is an answer. When that answer is missing, only the caller’s timer can end the attempt.

6. What a Shell Reports, and What a Retry Costs

The cheapest field test is a shell, because curl’s exit status separates the two conditions. The five commands below ran against one closed port and one silent port on this host; the port numbers in the transcripts are whatever the probe received.

CommandExit statusWhat it printed
curl, closed portexit 7“Could not connect to server”, after 0 ms
curl, silent port, 2 s limitexit 28“Connection timed out”, after the limit
bash /dev/tcp, closed portexit 1“connect: Connection refused”
dash /dev/tcp, closed portexit 2“Directory nonexistent”: the shell has no such path
python3 -c, closed portexit 1a traceback ending in ConnectionRefusedError
Table 6: Five ways a shell or an interpreter reports the same closed port.

The curl pair is the one to remember, because it is the one tool here whose own exit status distinguishes the two conditions: 7 means the connect failed and 28 means the operation ran out of time, and the first is a refusal while the second is usually silence (curl’s exit codes). The dash row is the trap: /dev/tcp is a bash feature, and a script that runs under /bin/sh on a Debian host reports a missing directory for a port that would have refused.

The same check as two copyable commands

/bin/bash -c 'exec 3<>/dev/tcp/127.0.0.1/9000'
echo "status: $?"
curl -sS --max-time 2 "http://127.0.0.1:9000/health"
echo "curl exit: $?"

Both snippets end with the status rather than the message, because the status is what a health check can act on. The first prints the shell’s own status after the redirection failed; the second prints curl’s, the only one of the two that distinguishes a refusal from a timeout.

What that distinction costs in time is the other half of the decision, and each figure below was taken under a stated condition rather than in general. The first three rows time one connect per run over five runs; the figure is the median with the smallest and largest of the five in brackets. The last row is one loop of 1,000 connects per run, the same five runs, divided by 1,000.

What was timedMedian (range of five runs)What it is
connect to a closed port7.68 µs (6.83–58.07)the reset came back
connect to a listening port10.44 µs (9.70–27.11)the handshake completed
connect_ex to a closed port6.16 µs (5.79–67.58)the same answer without an exception
1,000 refused connects, per call12.3 µs (11.9–12.7)one loop, no wait between attempts
Table 7: What a refusal costs next to a connect that succeeds; the first three rows time one connect per run, the last one loop of 1,000, five runs each.

The other timings on the page keep their own conditions. The 38 µs in Table 4 is a single connect, timed once after a single accept, and the 2,002 ms beside it is one connect that waited out a two-second select on a queue that stayed full.

In Section 8 the 0.351 s is the median of five deploy races, and the 8.6 µs there is a median of five 0.2-second busy loops, each loop’s deadline divided by the refusals it managed. That 8.6 µs and the 12.3 µs in Table 7 are separate measurements, taken at different times in different loops on this guest, which shares its 2 vCPUs with whatever else is scheduled on it. The page did not time the two side by side, so it does not claim what separates them.

A refusal is the price of a system call, not the price of a wait. 7.68 µs is the median of one connect against a closed port and 10.44 µs the median of one that completed its handshake; the two bands overlap on this guest, so read the gap as small rather than as a ranking.

The thousand-call row is what a retry loop actually pays: 12.3 µs (11.9–12.7) per refused attempt when the caller never waits between them. That is what makes a retry against a port that is not up yet cheap, and a retry without any wait useless: the busy loop in Section 8 made 23,255 refusals and connected on none of them.

7. A Module That Makes the Difference Visible

The rest of this page assumes a caller can tell four conditions apart and say which one it met, and can name the fifth answer it gives to anything else. That is a small amount of code and a large amount of discipline: one mapping from errno to a word, five strings in all – refused, timeout, unreachable, not_resolved and the fallback other – one sentence of advice per word, one connect that tries every address a name returned, one probe that keeps “closed” and “silent” apart, and one loop that spends a deadline instead of a count. The module is 202 lines in 5 files, with 25 tests printed in Appendix A; this section quotes the two decisions that carry the policy.

The first is the classification. It returns a word rather than raising a new exception, because the caller usually wants to log the condition and choose a policy instead of wrapping the error again.

"""Name the condition behind a failed connect, in the words an operator uses.

A closed port arrives as ``ECONNREFUSED``, a dropped SYN as ``TimeoutError``, an unroutable
address as ``ENETUNREACH`` or ``EHOSTUNREACH``, and a rejected name as ``gaierror``. The
difference decides whether a retry is right.
"""

import errno
import socket

REFUSED = "refused"
TIMEOUT = "timeout"
UNREACHABLE = "unreachable"
NOT_RESOLVED = "not_resolved"
OTHER = "other"
_BY_NUMBER = {
    errno.ECONNREFUSED: REFUSED,
    errno.ETIMEDOUT: TIMEOUT,
    errno.ENETUNREACH: UNREACHABLE,
    errno.EHOSTUNREACH: UNREACHABLE,
    errno.EADDRNOTAVAIL: UNREACHABLE,
}
_ADVICE = {
    REFUSED: "the address answered with a reset: retry only while the peer is expected to start",
    TIMEOUT: "nothing answered: check the path or the firewall before retrying",
    UNREACHABLE: "the kernel has no route to that address: fix the address or the route",
    NOT_RESOLVED: "the name did not resolve: fix the resolver or use the address",
    OTHER: "read the exception: this is not one of the four conditions this module names",
}


def explain(exc: BaseException) -> str:
    """The condition this exception names, or OTHER when it names none of them."""
    if isinstance(exc, socket.gaierror):
        return NOT_RESOLVED
    number = getattr(exc, "errno", None)
    if number in _BY_NUMBER:
        return _BY_NUMBER[number]
    if isinstance(exc, TimeoutError):
        return TIMEOUT
    return OTHER


def is_refused(exc: BaseException) -> bool:
    """True only for the reset: the peer's host is up and the port is not accepting."""
    return explain(exc) == REFUSED


def advice(reason: str) -> str:
    """One sentence per condition, so a caller does not have to remember the table."""
    return _ADVICE.get(reason, _ADVICE[OTHER])

Two details in that code are deliberate. gaierror is checked before the errno, because a resolver failure carries a negative number rather than one of the kernel’s; TimeoutError is checked after the errno table, because Python’s socket timeout is that class and carries no errno at all. The advice strings are the page’s policy in one place: a refusal is worth a retry inside a deadline, a timeout is a question about the path, and an unreachable address or an unresolved name is neither.

Exception handed inCondition returnedWhat a caller should do
ConnectionRefusedError (111)refusedretry to the deadline; the port is closed now
OSError 110timeoutcheck the path or the firewall; a retry repeats the silence
OSError 113unreachablefix the address or the route
socket.gaierrornot_resolvedfix the resolver or pass the address
OSError carrying any other numberotherread the exception; it is a local bug, not a network answer
Table 8: Five exceptions and the one word each becomes.

The second decision is the loop. It takes a deadline in seconds rather than an attempt count, because the peer’s readiness is measured in wall-clock time; it doubles its wait up to a cap, and it cuts the last wait to whatever is left so it never sleeps past the deadline it was given.

"""Delays between attempts, and the loop that spends them inside a deadline.

The delays double from ``base`` to ``cap``, and the last wait is cut to what is left.
"""

import time

BASE = 0.05
CAP = 0.5


def delays(count: int, base: float = BASE, cap: float = CAP) -> tuple[float, ...]:
    """The waits after each of ``count`` failed attempts: 50 ms, 100 ms, 200 ms, 500 ms..."""
    out: list[float] = []
    wait = base
    for _ in range(count):
        out.append(round(wait, 4))
        wait = min(cap, wait * 2)
    return tuple(out)


def retry(connect, deadline_s: float, base: float = BASE, cap: float = CAP,
          clock=time.monotonic, sleep=time.sleep) -> dict:
    """Call ``connect`` until it returns or the deadline passes.

    The result always says how many attempts were made, what the last error was and how long
    the waits were, so a caller can log a refusal that ended in a connection and a refusal
    that ended in a deadline differently.
    """
    started = clock()
    waits: list[float] = []
    attempts = 0
    last: BaseException | None = None
    while True:
        attempts += 1
        try:
            sock = connect()
        except OSError as exc:
            last = exc
            left = deadline_s - (clock() - started)
            if left <= 0:
                break
            wait = min(cap, base * 2 ** (attempts - 1), left)
            waits.append(round(wait, 4))
            sleep(wait)
            continue
        return {"socket": sock, "attempts": attempts, "waits": waits,
                "elapsed_s": round(clock() - started, 4), "error": None}
    return {"socket": None, "attempts": attempts, "waits": waits,
            "elapsed_s": round(clock() - started, 4), "error": last}

The other two pieces are named in the table below and printed whole in Appendix A. dial_any tries every address a name returned and keeps the failures instead of re-raising them, because a refusal on the first address says nothing about the second. port_state answers “open”, “closed”, “silent” or “unresolved”, so a health check can tell a stopped service from a dropped packet.

closed port: closed
open port: open
full queue: silent
unresolved name: unresolved
a reset is: refused
waits: 0.05 0.1 0.2 0.4 0.5
advice: the address answered with a reset: retry only while the peer is expected to start

Run the four pieces together and the answers are the ones the page has been claiming, in one page of output. The module’s own records are the closing table: the retry rows are the interesting ones, with a loop that connected on attempt 4 after 0.351 s against a service that started late, and one that spent its whole deadline on 4 attempts against a port that stayed closed.

CallWhat it answeredWhat the answer is for
dial on a closed portConnectionRefusedError, reason refusedthe exception is the answer
dial_any, one address closed and the next openconnected, 1 failure keptthe refusal is recorded, not raised
port_state on a live and a closed portopen and closedthe two states a health check needs
port_state, full accept queuesilentnot the same word as closed
port_state, rejected nameunresolvedfails before a socket exists
retry, service up after the first refusal4 attempts, 0.351 sthe waits doubled from the base
retry, port stays closed4 attempts, 0.300 sthe deadline ends on refused, not on a timeout
Table 9: Seven answers from the module, each traced to one arm of the probe.

8. Deploying the Change: One Decision per Surface

A refusal is the normal state of a service during its own deploy: the ports of a restarting container and of a process that has bound but not yet listened are closed for a moment, and every client that arrives in that moment is refused. The table below is that moment measured, with the service starting to listen 250 ms after the caller’s first attempt.

Client habitWhat happenedWhat it says about the habit
one dial, no retry111 ECONNREFUSEDthe deploy looks like an outage
retry to a deadline of 2 sconnected on attempt 4 after 0.351 s (0.351–0.360)the waits doubled from the base to the cap
sleep 1 s, then one dialconnected 5 times out of 5works, and always costs the full second
busy loop for as long as the deadline23,255 refusals, none connectedburns the deadline without waiting for the peer
Table 10: The same deploy met by four client habits, five runs each.

The deadline loop is the one that generalises, and the numbers say why: the peer needed wall-clock time, and both a fixed sleep and a busy loop spend it worse. The fixed sleep spends a full second even when the port opened after a third of it, and the busy loop spends the deadline making tens of thousands of refusals at 8.6 µs each on average, which is a CPU story rather than a connection story. What the loop gives instead is an attempt count and an elapsed time that can be logged, which is what turns “the deploy failed” into “four attempts in 0.351 seconds”.

SurfaceChange to makeWhat the change buys
Command-line tool or cron jobone attempt, then report the reason and the exit statusa refusal is a fact about the target
Worker calling a peer that may be restartingretry only a refusal, to a deadline, with a doubling waita rolling deploy stops looking like an outage
Health check or readiness probeask with port_state and report closed and silent aparta stopped service and a dropped packet raise different alerts
Supervisor or orchestratorrecord the first refusal’s time and the attempt that succeededthe deploy’s real startup time becomes visible
Service that binds a specific addressbind the address its clients use, or the wildcard, and print the bound addressa refusal from an address mismatch the log can show
Proxy or sidecarlog the address it dialled with the refusal, not the service namethe next reader knows which hop said no
Table 11: Six surfaces and the one decision each needs after a refused connect.

Three commitments hold across the table: classify before deciding, keep the refusal and the timeout apart in what the caller logs, and bound every retry by a deadline the caller chose. Anything else turns a refused port into an outage of its own.

The numbers on other platforms are close but not identical, and a client that hard-codes 111 misreads them. The table marks what was measured here and what comes from the platform’s own headers and reference pages.

PlatformWhat a closed port is calledHow this page knows
Linux, TCP111 ECONNREFUSEDmeasured on this host; errno(3) lists the same number
Linux, unix socket111 ECONNREFUSED; 2 ENOENT when the path is absentmeasured on this host
macOS61 ECONNREFUSEDdocumented, not measured here: the same name, a different number (xnu bsd/sys/errno.h)
Windows10061 WSAECONNREFUSEDdocumented, not measured here: a Winsock code, not an errno (Winsock error codes)
Table 12: Four names for the same condition, with the measured rows marked.

A refusal is also the wrong place to stop looking. It says the port is closed at that address now, and the next question is which of the four owns it. The runbooks that follow this page take the same host apart for the neighbouring conditions: the EADDRINUSE runbook for the bind that fails because the port is taken, the accept-queue runbook for connects that stall at one, three and seven seconds, and the EPIPE runbook for the peer that leaves after the connection was made.

Questions This Page Answers

Is connection refused the same as unreachable?

No. A refusal is an answer: the peer’s stack received the SYN and sent a reset because no socket was listening at that address and port (errno 111). Unreachable is a local refusal – ENETUNREACH (101) or EHOSTUNREACH (113) – meaning the kernel had no route to send the packet.

Why is the connection refused when the service is running?

Because the listener is bound to a different address, has not called listen, or is gone and left a socket file behind. On this host a listener on 127.0.0.1 refused a client dialling 127.0.0.2, and a socket bound but never listened refused every client.

Can a firewall produce connection refused?

Yes, if it rejects with a reset. A firewall that drops instead produces silence, and the client reports its own timeout. The cheap test is a port on the same host that nothing could be listening on: if that one is refused while the service port is silent, the firewall is dropping the service port.

Why did the connect time out instead of being refused when the server was busy?

Because the accept queue was full and this host’s tcp_abort_on_overflow is 0, so the extra SYN was dropped rather than reset. The listener was up and healthy; the queue was the limit.

Is the accept queue really the backlog plus one?

It held listen(n)+1 here, and the kernel source says why: sk_acceptq_is_full() tests sk_ack_backlog > sk_max_ack_backlog with a strict >, so n+1 completed connections fit and the n+2th is turned away – not a slot reserved for a handshake in progress. The backlog is still clipped to net.core.somaxconn (4,096 here).

Should I retry a refused connection?

Yes, while the peer is expected to be starting, and only inside a deadline. In the deploy measured here the port opened after 250 ms and a loop with a doubling wait connected on attempt 4. A retry with no deadline turns a refusal into a hang, and a retry with no wait just spends CPU.

Why does my code see ConnectionRefusedError but the library does not?

Because the library wraps it. On this host requests raised a ConnectionError whose chain ended in ConnectionRefusedError, and aiohttp a ClientConnectorError carrying errno 111. Log the class, the errno and the chain rather than str(exc).

What is the shortest change that makes this visible?

Classify the exception into refused, timeout, unreachable or not_resolved, log that word with the address, and retry only the refused case inside a deadline. That is the whole policy this page argues for, and it is what the module in Section 7 implements.

Other errno runbooks: Zero-Crash Python.

TechBobby Engineering. Appendix A prints the module and its 25 tests; Appendix B prints every probe behind a figure in this page.

Appendix A: The Module and Its Tests, Printed Whole

The folds below print the module and its tests character for character, so the tree can be rebuilt from this page without a repository: five module files, then the four test files that pytest connectguard/tests runs, 25 in all.

the exports connectguard/__init__.py
"""connectguard: say which kind of failure a connect met, and retry only the ones worth it."""
from .backoff import delays, retry
from .dial import dial, dial_any
from .errors import NOT_RESOLVED, OTHER, REFUSED, TIMEOUT, UNREACHABLE, advice, explain, is_refused
from .probe import port_state

__all__ = [
    "NOT_RESOLVED", "OTHER", "REFUSED", "TIMEOUT", "UNREACHABLE",
    "advice", "explain", "is_refused", "dial", "dial_any", "delays", "retry", "port_state",
]
the four conditions and their sentences connectguard/errors.py
"""Name the condition behind a failed connect, in the words an operator uses.

A closed port arrives as ``ECONNREFUSED``, a dropped SYN as ``TimeoutError``, an unroutable
address as ``ENETUNREACH`` or ``EHOSTUNREACH``, and a rejected name as ``gaierror``. The
difference decides whether a retry is right.
"""
from __future__ import annotations

import errno
import socket

REFUSED = "refused"
TIMEOUT = "timeout"
UNREACHABLE = "unreachable"
NOT_RESOLVED = "not_resolved"
OTHER = "other"

_BY_NUMBER = {
    errno.ECONNREFUSED: REFUSED,
    errno.ETIMEDOUT: TIMEOUT,
    errno.ENETUNREACH: UNREACHABLE,
    errno.EHOSTUNREACH: UNREACHABLE,
    errno.EADDRNOTAVAIL: UNREACHABLE,
}

_ADVICE = {
    REFUSED: "the address answered with a reset: retry only while the peer is expected to start",
    TIMEOUT: "nothing answered: check the path or the firewall before retrying",
    UNREACHABLE: "the kernel has no route to that address: fix the address or the route",
    NOT_RESOLVED: "the name did not resolve: fix the resolver or use the address",
    OTHER: "read the exception: this is not one of the four conditions this module names",
}


def explain(exc: BaseException) -> str:
    """The condition this exception names, or OTHER when it names none of them."""
    if isinstance(exc, socket.gaierror):
        return NOT_RESOLVED
    number = getattr(exc, "errno", None)
    if number in _BY_NUMBER:
        return _BY_NUMBER[number]
    if isinstance(exc, TimeoutError):
        return TIMEOUT
    return OTHER


def is_refused(exc: BaseException) -> bool:
    """True only for the reset: the peer's host is up and the port is not accepting."""
    return explain(exc) == REFUSED


def advice(reason: str) -> str:
    """One sentence per condition, so a caller does not have to remember the table."""
    return _ADVICE.get(reason, _ADVICE[OTHER])
one address, and every address a name returned connectguard/dial.py
"""One connect to one address, and one that tries every address a name resolves to."""
from __future__ import annotations

import errno
import socket


def dial(host: str, port: int, timeout: float = 2.0,
         family: int = socket.AF_UNSPEC) -> socket.socket:
    """Connect to the first address this name resolves to, or raise what the connect raised."""
    answers = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
    af, kind, proto, _, address = answers[0]
    sock = socket.socket(af, kind, proto)
    sock.settimeout(timeout)
    try:
        sock.connect(address)
        return sock
    except OSError:
        sock.close()
        raise


def dial_any(host: str, port: int, timeout: float = 2.0, family: int = socket.AF_UNSPEC,
             answers: list[tuple] | None = None) -> tuple[socket.socket, list[dict]]:
    """Try each resolved address; return the first socket that connects and every failure.

    ``answers`` lets a caller hand over the list the resolver already returned, so a client that
    logs its resolution does not resolve the name twice.
    """
    if answers is None:
        answers = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
    failures: list[dict] = []
    for af, kind, proto, _, address in answers:
        sock = socket.socket(af, kind, proto)
        sock.settimeout(timeout)
        try:
            sock.connect(address)
            return sock, failures
        except OSError as exc:
            sock.close()
            failures.append({"address": f"{address[0]}:{address[1]}", "family": af,
                             "errno": exc.errno, "exception": type(exc).__name__})
    if not failures:
        raise OSError("the name resolved to no address")
    # Re-raise the last failure as the kind it was: a name whose last address timed out
    # failed with a timeout, not with the refusal an earlier address gave.
    last = failures[-1]
    message = f"every address for {host}:{port} failed; last {last['address']}"
    if last["exception"] == "TimeoutError":
        raise TimeoutError(message)
    if last["errno"] == errno.ECONNREFUSED:
        raise ConnectionRefusedError(last["errno"], message)
    raise OSError(last["errno"] or 0, message)
the waits and the deadline loop connectguard/backoff.py
"""Delays between attempts, and the loop that spends them inside a deadline.

The delays double from ``base`` to ``cap``, and the last wait is cut to what is left.
"""
from __future__ import annotations

import time

BASE = 0.05
CAP = 0.5


def delays(count: int, base: float = BASE, cap: float = CAP) -> tuple[float, ...]:
    """The waits after each of ``count`` failed attempts: 50 ms, 100 ms, 200 ms, 500 ms..."""
    out: list[float] = []
    wait = base
    for _ in range(count):
        out.append(round(wait, 4))
        wait = min(cap, wait * 2)
    return tuple(out)


def retry(connect, deadline_s: float, base: float = BASE, cap: float = CAP,
          clock=time.monotonic, sleep=time.sleep) -> dict:
    """Call ``connect`` until it returns or the deadline passes.

    The result always says how many attempts were made, what the last error was and how long
    the waits were, so a caller can log a refusal that ended in a connection and a refusal
    that ended in a deadline differently.
    """
    started = clock()
    waits: list[float] = []
    attempts = 0
    last: BaseException | None = None
    while True:
        attempts += 1
        try:
            sock = connect()
        except OSError as exc:
            last = exc
            left = deadline_s - (clock() - started)
            if left <= 0:
                break
            wait = min(cap, base * 2 ** (attempts - 1), left)
            waits.append(round(wait, 4))
            sleep(wait)
            continue
        return {"socket": sock, "attempts": attempts, "waits": waits,
                "elapsed_s": round(clock() - started, 4), "error": None}
    return {"socket": None, "attempts": attempts, "waits": waits,
            "elapsed_s": round(clock() - started, 4), "error": last}
closed, silent, unreachable, unresolved connectguard/probe.py
"""What a port answers, in one word, for a health check that must not lie.

A refusal proves the port is closed; silence proves only that nothing answered within the
timeout. A check that reports both as "down" cannot tell a stopped service from a dropped
packet.
"""
from __future__ import annotations

from .dial import dial
from .errors import explain

OPEN = "open"
CLOSED = "closed"
SILENT = "silent"
UNREACHABLE = "unreachable"
UNRESOLVED = "unresolved"
UNKNOWN = "unknown"

_STATE = {
    "refused": CLOSED,
    "timeout": SILENT,
    "unreachable": UNREACHABLE,
    "not_resolved": UNRESOLVED,
}


def port_state(host: str, port: int, timeout: float = 1.0) -> str:
    """Ask once and answer with the state, closing the socket if the port is open."""
    try:
        sock = dial(host, port, timeout=timeout)
    except OSError as exc:
        return _STATE.get(explain(exc), UNKNOWN)
    sock.close()
    return OPEN
the mapping and the sentences connectguard/tests/test_errors.py
"""The four conditions, and the one that is not an exception number at all."""
from __future__ import annotations

import errno
import socket

from connectguard import errors


def test_a_reset_is_named_refused():
    assert errors.explain(ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused")) == \
        errors.REFUSED


def test_the_kernel_timeout_is_named_timeout():
    assert errors.explain(OSError(errno.ETIMEDOUT, "Connection timed out")) == errors.TIMEOUT


def test_pythons_socket_timeout_is_named_timeout():
    assert errors.explain(TimeoutError("timed out")) == errors.TIMEOUT


def test_a_route_failure_is_named_unreachable():
    assert errors.explain(OSError(errno.ENETUNREACH, "Network is unreachable")) == \
        errors.UNREACHABLE
    assert errors.explain(OSError(errno.EHOSTUNREACH, "No route to host")) == errors.UNREACHABLE


def test_a_rejected_name_is_named_not_resolved():
    assert errors.explain(socket.gaierror(-2, "Name or service not known")) == \
        errors.NOT_RESOLVED


def test_anything_else_is_named_other():
    assert errors.explain(OSError(errno.EBADF, "Bad file descriptor")) == errors.OTHER


def test_only_the_reset_counts_as_refused():
    assert errors.is_refused(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) is True
    assert errors.is_refused(TimeoutError("timed out")) is False


def test_every_condition_has_a_sentence_of_its_own():
    sentences = {errors.advice(reason) for reason in
                 (errors.REFUSED, errors.TIMEOUT, errors.UNREACHABLE, errors.NOT_RESOLVED,
                  errors.OTHER)}
    assert len(sentences) == 5


def test_an_unknown_reason_falls_back_to_the_other_sentence():
    assert errors.advice("made_up") == errors.advice(errors.OTHER)
one address and the list of them connectguard/tests/test_dial.py
"""One address and every address: the difference a hostname makes."""
from __future__ import annotations

import socket

import pytest

from connectguard import dial, dial_any


def free_port() -> int:
    sock = socket.socket()
    try:
        sock.bind(("127.0.0.1", 0))
        return sock.getsockname()[1]
    finally:
        sock.close()


@pytest.fixture()
def listener():
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(8)
    server.settimeout(2.0)
    try:
        yield server
    finally:
        server.close()


def answer(address: tuple[str, int]) -> tuple:
    return (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", address)


def test_dial_returns_a_connected_socket(listener):
    sock = dial("127.0.0.1", listener.getsockname()[1], timeout=1.0)
    try:
        sock.send(b"hello")
        conn, _ = listener.accept()
        try:
            assert conn.recv(16) == b"hello"
        finally:
            conn.close()
    finally:
        sock.close()


def test_dial_raises_the_refusal_it_met():
    with pytest.raises(ConnectionRefusedError) as caught:
        dial("127.0.0.1", free_port(), timeout=1.0)
    assert caught.value.errno == 111


def test_dial_any_walks_past_a_refused_address(listener):
    answers = [answer(("127.0.0.1", free_port())),
               answer(("127.0.0.1", listener.getsockname()[1]))]
    sock, failures = dial_any("127.0.0.1", 0, answers=answers)
    try:
        assert sock.fileno() >= 0
        assert len(failures) == 1
        assert failures[0]["errno"] == 111
        assert failures[0]["exception"] == "ConnectionRefusedError"
    finally:
        sock.close()


def test_dial_any_reports_every_address_when_all_fail():
    first, second = free_port(), free_port()
    with pytest.raises(ConnectionRefusedError) as caught:
        dial_any("127.0.0.1", 0, answers=[answer(("127.0.0.1", first)),
                                          answer(("127.0.0.1", second))])
    assert str(second) in str(caught.value)


def test_dial_any_keeps_the_kind_of_the_last_failure():
    """A name whose last address timed out did not fail with a refusal."""
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("127.0.0.1", 0))
    listener.listen(0)
    filler = socket.socket()
    filler.settimeout(1.0)
    try:
        filler.connect(listener.getsockname())
        with pytest.raises(TimeoutError) as caught:
            dial_any("127.0.0.1", 0, timeout=0.2,
                     answers=[answer(("127.0.0.1", listener.getsockname()[1]))])
        assert not isinstance(caught.value, ConnectionRefusedError)
    finally:
        filler.close()
        listener.close()


def test_dial_any_without_an_address_raises():
    with pytest.raises(OSError):
        dial_any("127.0.0.1", 0, answers=[])
the waits and the deadline connectguard/tests/test_backoff.py
"""The waits, and a loop that must not sleep past its deadline."""
from __future__ import annotations

import errno

from connectguard import backoff


class Clock:
    """A clock that moves only when the loop sleeps."""

    def __init__(self) -> None:
        self.now = 0.0

    def time(self) -> float:
        return self.now

    def sleep(self, seconds: float) -> None:
        self.now += seconds


def test_the_waits_double_from_the_base_to_the_cap():
    assert backoff.delays(4) == (0.05, 0.1, 0.2, 0.4)


def test_the_waits_stop_at_the_cap():
    assert backoff.delays(6) == (0.05, 0.1, 0.2, 0.4, 0.5, 0.5)


def test_the_base_and_the_cap_are_the_callers():
    assert backoff.delays(3, base=0.1, cap=0.3) == (0.1, 0.2, 0.3)


def test_the_loop_returns_the_socket_when_an_attempt_succeeds():
    clock = Clock()
    calls = []

    def connect():
        calls.append(clock.time())
        if len(calls) < 3:
            raise ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused")
        return "socket"

    result = backoff.retry(connect, deadline_s=5.0, clock=clock.time, sleep=clock.sleep)
    assert result["socket"] == "socket"
    assert result["attempts"] == 3
    assert result["waits"] == [0.05, 0.1]
    assert result["error"] is None


def test_the_loop_stops_at_the_deadline_with_the_last_error():
    clock = Clock()

    def connect():
        raise ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused")

    result = backoff.retry(connect, deadline_s=0.2, clock=clock.time, sleep=clock.sleep)
    assert result["socket"] is None
    assert isinstance(result["error"], ConnectionRefusedError)
    assert clock.now <= 0.2
    assert sum(result["waits"]) == round(clock.now, 4)


def test_the_last_wait_is_cut_to_what_is_left():
    clock = Clock()

    def connect():
        raise TimeoutError("timed out")

    result = backoff.retry(connect, deadline_s=0.12, clock=clock.time, sleep=clock.sleep)
    assert result["waits"][-1] < 0.1
    assert clock.now == 0.12
four states of a port connectguard/tests/test_probe.py
"""A health check that tells a closed port from a silent one."""
from __future__ import annotations

import socket

import pytest

from connectguard import probe


@pytest.fixture()
def listener():
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    try:
        yield server
    finally:
        server.close()


def free_port() -> int:
    sock = socket.socket()
    try:
        sock.bind(("127.0.0.1", 0))
        return sock.getsockname()[1]
    finally:
        sock.close()


def test_an_open_port_is_open(listener):
    assert probe.port_state("127.0.0.1", listener.getsockname()[1], timeout=1.0) == probe.OPEN


def test_a_closed_port_is_closed():
    assert probe.port_state("127.0.0.1", free_port(), timeout=1.0) == probe.CLOSED


def test_a_full_accept_queue_is_silent():
    """The listener is up but cannot take another connection: no answer, no refusal."""
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(0)
    port = server.getsockname()[1]
    filler = socket.socket()
    filler.settimeout(1.0)
    try:
        filler.connect(("127.0.0.1", port))
        assert probe.port_state("127.0.0.1", port, timeout=0.2) == probe.SILENT
    finally:
        filler.close()
        server.close()


def test_a_name_the_resolver_rejects_is_unresolved():
    assert probe.port_state("no-such-host.invalid", 80, timeout=1.0) == probe.UNRESOLVED

Appendix B: The Probes, Printed Whole

These produced every figure in Tables 2 through 10 and the counts the body quotes about its own tree. Each writes one record under results/ with the runs its table shows – five for a timing row, one for an errno – and the helper they share comes first.

one record, five runs when a row asks for them sandbox/probelib.py
"""Shared helpers for the connect probes: one record per probe, one or five runs per arm."""
from __future__ import annotations

import json
import pathlib
import socket
import time

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"


def write(name: str, payload: dict) -> pathlib.Path:
    RESULTS.mkdir(parents=True, exist_ok=True)
    path = RESULTS / f"{name}.json"
    path.write_text(json.dumps(payload, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    return path


def record(probe: str, note: str, arms: list[dict], **extra) -> dict:
    return {"probe": probe, "note": note, "arms": arms, **extra}


def repeat(label: str, fn, times: int = 5) -> dict:
    runs = []
    for _ in range(times):
        runs.append(fn())
    return {"label": label, "runs": runs}


def once(label: str, fn) -> dict:
    return {"label": label, "runs": [fn()]}


def free_port(host: str = "127.0.0.1") -> int:
    """A port nobody holds at the moment of the call, released before it is returned."""
    probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        probe.bind((host, 0))
        return probe.getsockname()[1]
    finally:
        probe.close()


def af_for(host: str) -> int:
    return socket.AF_INET6 if ":" in host else socket.AF_INET


def listening(host: str = "127.0.0.1", backlog: int = 16,
              port: int = 0) -> socket.socket:
    """A listening socket on the address given, ready for a connect."""
    family = af_for(host)
    sock = socket.socket(family, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock


def connect(host: str, port: int, timeout: float = 2.0, family: int | None = None,
            source: str | None = None) -> dict:
    """One connect attempt, reported as what the caller would have to handle."""
    family = family or af_for(host)
    sock = socket.socket(family, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    if source is not None:
        sock.bind((source, 0))
    started = time.perf_counter_ns()
    try:
        sock.connect((host, port))
        return {"ok": True, "errno": None, "exception": None, "ns": time.perf_counter_ns() - started,
                "peer": list(sock.getpeername()[:2])}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
                "message": exc.strerror, "ns": time.perf_counter_ns() - started}
    finally:
        sock.close()


def accept_queue(port: int, host: str = "127.0.0.1") -> int | None:
    """The listener's accept queue length, read from /proc/net/tcp{,6} rather than assumed."""
    path = "/proc/net/tcp6" if ":" in host else "/proc/net/tcp"
    try:
        lines = pathlib.Path(path).read_text().splitlines()[1:]
    except OSError:
        return None
    for line in lines:
        fields = line.split()
        if len(fields) < 10:
            continue
        local, state, queue = fields[1], fields[3], fields[4]
        if state != "0A":
            continue
        address, _, port_hex = local.rpartition(":")
        if int(port_hex, 16) != port:
            continue
        if host == "127.0.0.1" and not address.endswith("0100007F"):
            continue
        # tx_queue:rx_queue; for a listener rx_queue is the accept queue.
        return int(queue.split(":")[1], 16)
    return None
the host, the numbers and the two names sandbox/01_facts.py
"""The host, the numbers this kernel uses, and the two names a client may have to resolve."""
from __future__ import annotations

import errno
import os
import platform
import socket
import subprocess

import probelib


def read(path: str) -> str | None:
    try:
        return open(path, encoding="utf-8").read().strip()
    except OSError:
        return None


def tool_version(argv: list[str]) -> str:
    result = subprocess.run(argv, capture_output=True, text=True)
    text = (result.stdout or result.stderr).strip().splitlines()
    return text[0] if text else ""


def main() -> None:
    host = {
        "kernel": platform.release(),
        "python": platform.python_version(),
        "machine": platform.machine(),
        "cpus": os.cpu_count(),
        "page_size": os.sysconf("SC_PAGE_SIZE"),
        "sh": os.path.realpath("/bin/sh"),
        "curl": tool_version(["/bin/curl", "--version"]),
        "bash": tool_version(["/bin/bash", "--version"]),
        "uid": os.getuid(),
    }

    numbers = {}
    for name in ("ECONNREFUSED", "ETIMEDOUT", "ECONNRESET", "EADDRINUSE", "EADDRNOTAVAIL",
                 "ENETUNREACH", "EHOSTUNREACH", "ENOENT", "ENOTSOCK", "EPROTOTYPE", "EACCES",
                 "EAGAIN", "EINPROGRESS"):
        numbers[name] = int(getattr(errno, name))
    numbers["message_for_111"] = os.strerror(errno.ECONNREFUSED)
    numbers["os_strerror_110"] = os.strerror(errno.ETIMEDOUT)

    sysctls = {name: read(f"/proc/sys/net/{path}") for name, path in {
        "tcp_abort_on_overflow": "ipv4/tcp_abort_on_overflow",
        "tcp_syncookies": "ipv4/tcp_syncookies",
        "tcp_max_syn_backlog": "ipv4/tcp_max_syn_backlog",
        "somaxconn": "core/somaxconn",
        "ip_local_port_range": "ipv4/ip_local_port_range",
        "tcp_syn_retries": "ipv4/tcp_syn_retries",
        "tcp_retries2": "ipv4/tcp_retries2",
        "tcp_fin_timeout": "ipv4/tcp_fin_timeout",
    }.items()}

    # Writing the switch that would turn a full accept queue into a reset needs a privilege this
    # process does not have; the failure is the record, not a workaround.
    switch = {"path": "/proc/sys/net/ipv4/tcp_abort_on_overflow", "writable": None, "error": None}
    try:
        with open(switch["path"], "w", encoding="utf-8") as handle:
            handle.write(sysctls["tcp_abort_on_overflow"] or "0")
        switch["writable"] = True
    except OSError as exc:
        switch["writable"] = False
        switch["error"] = f"{type(exc).__name__}: {exc.strerror}"

    names = {}
    for name in ("localhost", "techbobby.com", "workspace"):
        try:
            answers = socket.getaddrinfo(name, 80, type=socket.SOCK_STREAM,
                                         proto=socket.IPPROTO_TCP)
            names[name] = {"ok": True,
                           "addresses": [{"family": str(answer[0].name),
                                          "address": answer[4][0]} for answer in answers]}
        except socket.gaierror as exc:
            names[name] = {"ok": False, "errno": exc.errno, "message": exc.strerror}

    loopbacks = {}
    for address in ("127.0.0.1", "127.0.0.2", "127.0.0.53", "127.0.0.254"):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind((address, 0))
            loopbacks[address] = "bindable"
        except OSError as exc:
            loopbacks[address] = f"{type(exc).__name__}: {exc.strerror}"
        finally:
            sock.close()

    interfaces = {}
    try:
        result = subprocess.run(["/usr/sbin/ip", "-o", "addr"], capture_output=True, text=True)
        interfaces["addresses"] = [line.strip() for line in result.stdout.splitlines()]
    except OSError as exc:
        interfaces["addresses"] = [f"{type(exc).__name__}"]
    interfaces["eth0_address"] = None
    for line in interfaces["addresses"]:
        if " eth0 " in line and "inet " in line:
            interfaces["eth0_address"] = line.split("inet ")[1].split("/")[0]

    hosts_file = {"exists": os.path.exists("/etc/hosts"),
                  "content": read("/etc/hosts")}
    resolv = read("/etc/resolv.conf")

    ipv6 = {"loopback_bindable": None, "error": None}
    try:
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.bind(("::1", 0))
        ipv6["loopback_bindable"] = True
        sock.close()
    except OSError as exc:
        ipv6["loopback_bindable"] = False
        ipv6["error"] = f"{type(exc).__name__}: {exc.strerror}"

    arms = [
        probelib.once("tcp_abort_on_overflow_switch", lambda: switch),
        probelib.once("name_lookup", lambda: names),
        probelib.once("loopback_addresses", lambda: loopbacks),
        probelib.once("interfaces", lambda: interfaces),
        probelib.once("hosts_file", lambda: hosts_file),
        probelib.once("ipv6_loopback", lambda: ipv6),
    ]

    payload = probelib.record(
        "01_facts",
        "host, errno numbers, the two kernel limits a refused connect depends on, and the names",
        arms, host=host, numbers=numbers, sysctls=sysctls, resolv_conf=resolv,
        documented={"ip_sysctl": "Documentation/networking/ip-sysctl.txt in the Linux tree",
                    "unix_7": "man7.org/linux/man-pages/man7/unix.7.html",
                    "tcp_ip": "RFC 9293 section 3.10.7.1 (reset generation)",
                    "python_errno": "docs.python.org/3/library/errno.html"})
    path = probelib.write("01_facts", payload)
    print("wrote", path)
    print("host", host)
    print("numbers", numbers)
    print("sysctls", sysctls)
    print("names", names)
    print("loopbacks", loopbacks)
    print("interfaces", interfaces["eth0_address"], interfaces["addresses"][:3])
    print("hosts", hosts_file, "resolv", resolv)
    print("ipv6", ipv6)


if __name__ == "__main__":
    main()
one port in eighteen arms, twelve of them printed in Table 3 sandbox/02_bind.py
"""What a client sees when the port is not the port the service is on.

Each arm builds one small situation, connects once, and reports the answer: an errno, a class,
or success.
"""
from __future__ import annotations

import os
import socket
import tempfile

import probelib


def with_listener(host: str, target: str, backlog: int = 8) -> dict:
    server = probelib.listening(host, backlog=backlog)
    port = server.getsockname()[1]
    try:
        return probelib.connect(target, port, timeout=2.0)
    finally:
        server.close()


def bound_not_listening(target: str) -> dict:
    """A descriptor holds the port, but nothing accepts on it."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("127.0.0.1", 0))
    port = sock.getsockname()[1]
    try:
        return probelib.connect(target, port, timeout=2.0)
    finally:
        sock.close()


def closed_after_listen(target: str) -> dict:
    """The service ran here and stopped: the port is free again."""
    server = probelib.listening("127.0.0.1")
    port = server.getsockname()[1]
    first = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    first.connect(("127.0.0.1", port))
    peer, _ = server.accept()
    peer.close()
    first.close()
    server.close()
    answer = probelib.connect(target, port, timeout=2.0)
    answer["port"] = port
    return answer


def udp_bound(target: str) -> dict:
    """A UDP listener holds the number; TCP has nothing to reach."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("127.0.0.1", 0))
    port = sock.getsockname()[1]
    try:
        return probelib.connect(target, port, timeout=2.0)
    finally:
        sock.close()


def unix_missing() -> dict:
    directory = tempfile.mkdtemp(prefix="connect_probe_")
    path = os.path.join(directory, "app.sock")
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.settimeout(2.0)
    try:
        sock.connect(path)
        return {"ok": True, "errno": None, "exception": None}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
                "message": exc.strerror}
    finally:
        sock.close()


def unix_stale() -> dict:
    """A socket file left behind by a server that exited."""
    directory = tempfile.mkdtemp(prefix="connect_probe_")
    path = os.path.join(directory, "app.sock")
    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(path)
    server.listen(4)
    server.close()          # the file stays; the listener does not
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.settimeout(2.0)
    try:
        sock.connect(path)
        return {"ok": True, "errno": None, "exception": None}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
                "message": exc.strerror, "file_still_there": os.path.exists(path)}
    finally:
        sock.close()


def unix_regular_file() -> dict:
    directory = tempfile.mkdtemp(prefix="connect_probe_")
    path = os.path.join(directory, "not-a-socket")
    with open(path, "w", encoding="utf-8") as handle:
        handle.write("x")
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.settimeout(2.0)
    try:
        sock.connect(path)
        return {"ok": True, "errno": None, "exception": None}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
                "message": exc.strerror}
    finally:
        sock.close()


def backlog_view(host: str = "127.0.0.1") -> dict:
    """The listener's own account of its queue, for the arm that fills it."""
    server = probelib.listening(host=host, backlog=4)
    port = server.getsockname()[1]
    pending = []
    try:
        for _ in range(3):
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.settimeout(2.0)
            client.connect((host, port))
            pending.append(client)
        queue = probelib.accept_queue(port, host)
        accepted = []
        server.settimeout(1.0)
        try:
            for _ in range(3):
                conn, _ = server.accept()
                accepted.append(True)
                conn.close()
        except socket.timeout:
            pass
        return {"completed_connects": len(pending), "queue_read": queue,
                "accepted": len(accepted)}
    finally:
        for client in pending:
            client.close()
        server.close()


def main() -> None:
    arms = [
        probelib.once("nothing_bound", lambda: probelib.connect("127.0.0.1",
                                                                probelib.free_port(), 2.0)),
        probelib.once("bound_not_listening", lambda: bound_not_listening("127.0.0.1")),
        probelib.once("listener_on_other_loopback",
                      lambda: with_listener("127.0.0.1", "127.0.0.2")),
        probelib.once("listener_on_second_loopback",
                      lambda: with_listener("127.0.0.2", "127.0.0.1")),
        probelib.once("wildcard_listener_loopback",
                      lambda: with_listener("0.0.0.0", "127.0.0.1")),
        probelib.once("wildcard_listener_second_loopback",
                      lambda: with_listener("0.0.0.0", "127.0.0.2")),
        probelib.once("wildcard_listener_nic", lambda: with_listener("0.0.0.0", "10.100.0.2")),
        probelib.once("nic_listener_loopback", lambda: with_listener("10.100.0.2", "127.0.0.1")),
        probelib.once("nic_listener_nic", lambda: with_listener("10.100.0.2", "10.100.0.2")),
        probelib.once("wildcard_listener_wildcard_destination",
                      lambda: with_listener("0.0.0.0", "0.0.0.0")),
        probelib.once("udp_holds_the_port", lambda: udp_bound("127.0.0.1")),
        probelib.once("port_free_after_the_service_stopped",
                      lambda: closed_after_listen("127.0.0.1")),
        probelib.once("unix_socket_missing", unix_missing),
        probelib.once("unix_socket_stale", unix_stale),
        probelib.once("unix_path_is_a_file", unix_regular_file),
        probelib.once("accept_queue_view", backlog_view),
        probelib.once("listen_backlog_zero", lambda: backlog_zero()),
        probelib.once("listen_backlog_huge", lambda: backlog_huge()),
    ]
    payload = probelib.record(
        "02_bind",
        "one connect per arm; the answer is an errno or success and does not move between runs",
        arms)
    path = probelib.write("02_bind", payload)
    print("wrote", path)
    for arm in arms:
        print(f"{arm['label']:36s} {arm['runs'][0]}")


def backlog_zero() -> dict:
    server = probelib.listening("127.0.0.1", backlog=0)
    port = server.getsockname()[1]
    try:
        answer = probelib.connect("127.0.0.1", port, timeout=2.0)
        answer["queue_after"] = probelib.accept_queue(port)
        return answer
    finally:
        server.close()


def backlog_huge() -> dict:
    server = probelib.listening("127.0.0.1", backlog=100000)
    port = server.getsockname()[1]
    try:
        answer = probelib.connect("127.0.0.1", port, timeout=2.0)
        answer["queue_after"] = probelib.accept_queue(port)
        return answer
    finally:
        server.close()


if __name__ == "__main__":
    main()
the accept queue and the connect after it sandbox/03_backlog.py
"""A listener that is up and not accepting: the queue filled without accept, read from /proc."""
from __future__ import annotations

import select
import socket
import time

import probelib


def fill(server: socket.socket, host: str, limit: int = 64) -> dict:
    """Connect until one attempt fails to complete, keeping the completed ones open."""
    port = server.getsockname()[1]
    done: list[socket.socket] = []
    failure = None
    try:
        for _ in range(limit):
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.settimeout(0.5)
            try:
                client.connect((host, port))
            except OSError as exc:
                failure = {"errno": exc.errno, "exception": type(exc).__name__}
                client.close()
                break
            done.append(client)
        queue = probelib.accept_queue(port, host)
        return {"completed": len(done), "queue": queue, "failure": failure}
    finally:
        for client in done:
            client.close()


def first_attempt(server: socket.socket, host: str, timeout: float = 2.0) -> dict:
    """One non-blocking connect to the full listener, read at the moments that differ."""
    port = server.getsockname()[1]
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.setblocking(False)
    started = time.perf_counter_ns()
    try:
        code = client.connect_ex((host, port))
        if code not in (0, 115):
            return {"connect_ex": code, "writable": None,
                    "ns": time.perf_counter_ns() - started}
        readable, writable, failed = select.select([], [client], [], timeout)
        elapsed = time.perf_counter_ns() - started
        answer = {"connect_ex": code, "writable": bool(writable),
                  "ns": elapsed, "socket_error": client.getsockopt(socket.SOL_SOCKET,
                                                                  socket.SO_ERROR)}
        if writable:
            client.setblocking(True)
            client.settimeout(1.5)
            try:
                answer["written"] = client.send(b"ping")
            except OSError as exc:
                answer["written"] = None
                answer["write_errno"] = exc.errno
                return answer
            try:
                answer["read"] = client.recv(16).decode("latin-1")
            except socket.timeout:
                answer["read"] = "timeout"
            except OSError as exc:
                answer["read"] = None
                answer["read_errno"] = exc.errno
        return answer
    finally:
        client.close()


def arm_full(backlog: int) -> dict:
    server = probelib.listening("127.0.0.1", backlog=backlog)
    try:
        filled = fill(server, "127.0.0.1")
        answer = {"backlog": backlog, **filled}
        answer["next"] = first_attempt(server, "127.0.0.1")
        return answer
    finally:
        server.close()


def arm_after_accept(backlog: int = 1) -> dict:
    """The queue drains by one: the same client that was silent now completes."""
    server = probelib.listening("127.0.0.1", backlog=backlog)
    try:
        filled = fill(server, "127.0.0.1")
        answer = {"backlog": backlog, **filled}
        answer["next_before_accept"] = first_attempt(server, "127.0.0.1", timeout=0.5)
        try:
            conn, _ = server.accept()
            conn.close()
            answer["accepted"] = 1
        except OSError:
            answer["accepted"] = 0
        answer["next_after_accept"] = first_attempt(server, "127.0.0.1", timeout=0.5)
        return answer
    finally:
        server.close()


def arm_accept_once(backlog: int = 1) -> dict:
    """One accept per round: the queue never fills, so every connect completes."""
    server = probelib.listening("127.0.0.1", backlog=backlog)
    port = server.getsockname()[1]
    try:
        outcomes = []
        for _ in range(3):
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.settimeout(1.0)
            try:
                client.connect(("127.0.0.1", port))
                conn, _ = server.accept()
                conn.close()
                outcomes.append("ok")
            except OSError as exc:
                outcomes.append(exc.errno)
            finally:
                client.close()
        return {"backlog": backlog, "outcomes": outcomes}
    finally:
        server.close()


def main() -> None:
    arms = [
        probelib.once("filled_backlog_one", lambda: arm_full(1)),
        probelib.once("filled_backlog_zero", lambda: arm_full(0)),
        probelib.once("filled_backlog_sixteen", lambda: arm_full(16)),
        probelib.once("drained_by_one_accept", lambda: arm_after_accept(1)),
        probelib.once("accept_each_round", lambda: arm_accept_once(1)),
    ]
    payload = probelib.record(
        "03_backlog",
        "the accept queue filled without accept(); the next connect is timed with select()",
        arms,
        documented={
            "abort_on_overflow": "ip-sysctl.txt: 0 means the kernel silently ignores the "
                                 "incoming ACK when the accept queue is full, 1 means it answers "
                                 "with a reset",
            "syn_retries": "tcp_syn_retries=6: the SYN is retried on the exponential backoff of "
                           "RFC 6298 until the connection attempt is abandoned",
            "somaxconn": "the backlog passed to listen() is clipped to net.core.somaxconn",
        })
    path = probelib.write("03_backlog", payload)
    print("wrote", path)
    for arm in arms:
        print(arm["label"], arm["runs"][0])


if __name__ == "__main__":
    main()
nine clients against one closed port, and two checks sandbox/04_python.py
"""One refused connect, told by every Python client a service is likely to use."""
from __future__ import annotations

import asyncio
import http.client
import socket
import urllib.error
import urllib.request

import probelib


def chain(exc: BaseException) -> dict:
    """Every wrapper a client puts around the same errno, outermost first."""
    names: list[str] = []
    errnos: list[int | None] = []
    current: BaseException | None = exc
    while current is not None and len(names) < 8:
        names.append(type(current).__name__)
        errnos.append(getattr(current, "errno", None))
        current = current.__cause__ or current.__context__
    leaf = next((number for number in reversed(errnos) if number), None)
    return {"chain": names, "leaf_errno": leaf}


def describe(exc: BaseException) -> dict:
    return {"exception": type(exc).__name__, "module": type(exc).__module__,
            "errno": getattr(exc, "errno", None),
            "message": getattr(exc, "strerror", None) or str(exc),
            "parents": [base.__name__ for base in type(exc).__mro__[1:6]]}


def port() -> int:
    return probelib.free_port()


def arm_socket_connect() -> dict:
    number = port()
    sock = socket.socket()
    sock.settimeout(2.0)
    try:
        sock.connect(("127.0.0.1", number))
        return {"connected": True}
    except OSError as exc:
        return {"connected": False, **describe(exc)}
    finally:
        sock.close()


def arm_connect_ex() -> dict:
    number = port()
    sock = socket.socket()
    try:
        return {"returned": sock.connect_ex(("127.0.0.1", number))}
    finally:
        sock.close()


def arm_create_connection() -> dict:
    number = port()
    try:
        socket.create_connection(("127.0.0.1", number), timeout=2.0)
        return {"connected": True}
    except OSError as exc:
        return {"connected": False, **describe(exc)}


def arm_urlopen() -> dict:
    number = port()
    try:
        urllib.request.urlopen(f"http://127.0.0.1:{number}/health", timeout=2.0)
        return {"connected": True}
    except urllib.error.URLError as exc:
        reason = exc.reason
        return {"connected": False, "exception": type(exc).__name__,
                "reason": type(reason).__name__,
                "reason_errno": getattr(reason, "errno", None),
                "message": str(exc)}


def arm_http_client() -> dict:
    number = port()
    connection = http.client.HTTPConnection("127.0.0.1", number, timeout=2.0)
    try:
        connection.request("GET", "/health")
        return {"connected": True}
    except OSError as exc:
        return {"connected": False, **describe(exc)}
    finally:
        connection.close()


def arm_requests() -> dict:
    import requests
    number = port()
    try:
        with requests.Session() as session:
            session.trust_env = False
            session.get(f"http://127.0.0.1:{number}/health", timeout=2.0)
        return {"connected": True}
    except requests.exceptions.ConnectionError as exc:
        return {"connected": False, "exception": type(exc).__name__, **chain(exc)}
    except requests.exceptions.RequestException as exc:
        return {"connected": False, "exception": type(exc).__name__, **chain(exc)}


def arm_httpx() -> dict:
    import httpx
    number = port()
    try:
        httpx.get(f"http://127.0.0.1:{number}/health", timeout=2.0, trust_env=False)
        return {"connected": True}
    except httpx.ConnectError as exc:
        return {"connected": False, "exception": type(exc).__name__, **chain(exc)}
    except httpx.HTTPError as exc:
        return {"connected": False, "exception": type(exc).__name__, **chain(exc)}


def arm_asyncio() -> dict:
    number = port()

    async def attempt() -> dict:
        try:
            reader, writer = await asyncio.open_connection("127.0.0.1", number)
        except OSError as exc:
            return {"connected": False, **describe(exc)}
        writer.close()
        return {"connected": True}

    return asyncio.run(attempt())


def arm_aiohttp() -> dict:
    import aiohttp

    async def attempt() -> dict:
        timeout = aiohttp.ClientTimeout(total=2.0)
        try:
            async with aiohttp.ClientSession(timeout=timeout, trust_env=False) as session:
                async with session.get(f"http://127.0.0.1:{port()}/health") as response:
                    return {"connected": True, "status": response.status}
        except OSError as exc:
            return {"connected": False, **describe(exc), **chain(exc)}

    return asyncio.run(attempt())


def arm_errno_strings() -> dict:
    number = port()
    sock = socket.socket()
    try:
        sock.connect(("127.0.0.1", number))
    except OSError as exc:
        return {"strerror": exc.strerror, "repr": repr(exc), "args": list(exc.args)}
    finally:
        sock.close()
    return {"strerror": None}


def arm_hierarchy() -> dict:
    number = port()
    sock = socket.socket()
    try:
        sock.connect(("127.0.0.1", number))
    except OSError as exc:
        return {"is_connection_refused": isinstance(exc, ConnectionRefusedError),
                "is_connection_error": isinstance(exc, ConnectionError),
                "is_oserror": isinstance(exc, OSError),
                "is_timeout": isinstance(exc, TimeoutError)}
    finally:
        sock.close()
    return {}


def main() -> None:
    arms = [
        probelib.once("socket_connect", arm_socket_connect),
        probelib.once("connect_ex", arm_connect_ex),
        probelib.once("create_connection", arm_create_connection),
        probelib.once("urllib", arm_urlopen),
        probelib.once("http_client", arm_http_client),
        probelib.once("requests", arm_requests),
        probelib.once("httpx", arm_httpx),
        probelib.once("asyncio", arm_asyncio),
        probelib.once("aiohttp", arm_aiohttp),
        probelib.once("errno_strings", arm_errno_strings),
        probelib.once("exception_hierarchy", arm_hierarchy),
    ]
    payload = probelib.record(
        "04_python",
        "nine clients and two checks against one closed loopback port; each answer is a "
        "class name or an errno",
        arms,
        documented={"library_docs": "requests, httpx and aiohttp document their exception "
                                    "hierarchies; the class names here are what this host's "
                                    "installed versions raised"})
    path = probelib.write("04_python", payload)
    print("wrote", path)
    for arm in arms:
        print(f"{arm['label']:22s} {arm['runs'][0]}")


if __name__ == "__main__":
    main()
five commands and their statuses sandbox/05_shell.py
"""What a shell reports for the same closed port: the exit status a supervisor actually sees."""
from __future__ import annotations

import socket
import subprocess

import probelib


def run(argv: list[str], timeout: float = 20.0) -> dict:
    result = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
    output = (result.stdout + result.stderr).strip().splitlines()
    return {"argv": argv[:3], "rc": result.returncode, "first_line": output[0] if output else "",
            "last_line": output[-1] if output else ""}


def main() -> None:
    number = probelib.free_port()
    server = probelib.listening("127.0.0.1", backlog=1)
    silent_port = server.getsockname()[1]
    # Fill the accept queue so that the port answers nothing, and keep it open for the arms.
    pending = []
    try:
        while True:
            client = socket.socket()
            client.settimeout(0.3)
            try:
                client.connect(("127.0.0.1", silent_port))
            except OSError:
                client.close()
                break
            pending.append(client)

        arms = [
            probelib.once("curl_refused",
                          lambda: run(["/bin/curl", "-sS", "--max-time", "3",
                                       f"http://127.0.0.1:{number}/health"])),
            probelib.once("curl_silent",
                          lambda: run(["/bin/curl", "-sS", "--max-time", "2",
                                       f"http://127.0.0.1:{silent_port}/health"])),
            probelib.once("bash_dev_tcp_refused",
                          lambda: run(["/bin/bash", "-c",
                                       f"exec 3<>/dev/tcp/127.0.0.1/{number} && echo opened"])),
            probelib.once("dash_dev_tcp_refused",
                          lambda: run(["/bin/dash", "-c",
                                       f"exec 3<>/dev/tcp/127.0.0.1/{number} && echo opened"])),
            probelib.once("python_traceback",
                          lambda: run(["python3", "-c",
                                       "import socket\n"
                                       f"socket.create_connection(('127.0.0.1', {number}), 2)\n"])),
        ]
        payload = probelib.record(
            "05_shell",
            "one closed port, one silent port: five ways a shell or an interpreter reports it",
            arms, closed_port=number, silent_port=silent_port,
            documented={"curl_exit": "curl's EXIT CODES section: 7 failed to connect, "
                                     "28 operation timeout"})
        path = probelib.write("05_shell", payload)
        print("wrote", path)
        for arm in arms:
            print(f"{arm['label']:26s} {arm['runs'][0]}")
    finally:
        for client in pending:
            client.close()
        server.close()


if __name__ == "__main__":
    main()
what each outcome costs sandbox/06_cost.py
"""What a refusal costs, next to a connect that succeeds, five runs each."""
from __future__ import annotations

import socket
import time

import probelib


def refused_connect() -> dict:
    number = probelib.free_port()
    sock = socket.socket()
    started = time.perf_counter_ns()
    try:
        sock.connect(("127.0.0.1", number))
        code = 0
    except OSError as exc:
        code = exc.errno
    finally:
        sock.close()
    return {"errno": code, "ns": time.perf_counter_ns() - started}


def established_connect(server: socket.socket) -> dict:
    port = server.getsockname()[1]
    sock = socket.socket()
    started = time.perf_counter_ns()
    try:
        sock.connect(("127.0.0.1", port))
        code = 0
    except OSError as exc:
        code = exc.errno
    finally:
        sock.close()
    return {"errno": code, "ns": time.perf_counter_ns() - started}


def connect_ex_call() -> dict:
    number = probelib.free_port()
    sock = socket.socket()
    started = time.perf_counter_ns()
    try:
        code = sock.connect_ex(("127.0.0.1", number))
    finally:
        sock.close()
    return {"returned": code, "ns": time.perf_counter_ns() - started}


def thousand_refusals() -> dict:
    number = probelib.free_port()
    started = time.perf_counter_ns()
    seen: dict[int, int] = {}
    for _ in range(1000):
        sock = socket.socket()
        try:
            sock.connect(("127.0.0.1", number))
        except OSError as exc:
            seen[exc.errno] = seen.get(exc.errno, 0) + 1
        finally:
            sock.close()
    total = time.perf_counter_ns() - started
    return {"calls": 1000, "ns_total": total, "ns_per_call": round(total / 1000),
            "errnos": seen}


def main() -> None:
    server = probelib.listening("127.0.0.1", backlog=512)
    try:
        arms = [
            probelib.repeat("refused_connect", refused_connect),
            probelib.repeat("established_connect", lambda: established_connect(server)),
            probelib.repeat("connect_ex_refused", connect_ex_call),
            probelib.repeat("thousand_refusals", thousand_refusals),
        ]
    finally:
        server.close()
    payload = probelib.record(
        "06_cost",
        "five runs per arm; a row prints its median and the range of its five runs",
        arms, repeats=5)
    path = probelib.write("06_cost", payload)
    print("wrote", path)
    for arm in arms:
        print(arm["label"], [run.get("ns") or run.get("ns_total") for run in arm["runs"]])


if __name__ == "__main__":
    main()
the module on the conditions it names sandbox/07_package.py
"""The package on the situations it names, and the two retry loops it offers."""
from __future__ import annotations

import socket
import threading
import time

import probelib

import connectguard


def explain_matrix() -> dict:
    cases = {
        "111": ConnectionRefusedError(111, "Connection refused"),
        "110": OSError(110, "Connection timed out"),
        "113": OSError(113, "No route to host"),
        "gai": socket.gaierror(-2, "Name or service not known"),
        "9": OSError(9, "Bad file descriptor"),
    }
    return {key: connectguard.explain(exc) for key, exc in cases.items()}


def dial_error() -> dict:
    number = probelib.free_port()
    try:
        connectguard.dial("127.0.0.1", number, timeout=2.0)
    except OSError as exc:
        return {"errno": exc.errno, "exception": type(exc).__name__,
                "reason": connectguard.explain(exc), "refused": connectguard.is_refused(exc)}
    return {"errno": None}


def dial_any_mixed() -> dict:
    server = probelib.listening("127.0.0.1")
    closed = probelib.free_port()
    port = server.getsockname()[1]
    answers = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", closed)),
               (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", port))]
    try:
        sock, failures = connectguard.dial_any("127.0.0.1", 0, answers=answers)
        sock.close()
        return {"connected": True, "failures": len(failures),
                "first_errno": failures[0]["errno"] if failures else None}
    finally:
        server.close()


def port_states() -> dict:
    listener = probelib.listening("127.0.0.1")
    port = listener.getsockname()[1]
    try:
        states = {"open": connectguard.port_state("127.0.0.1", port, timeout=1.0),
                  "closed": connectguard.port_state("127.0.0.1", probelib.free_port(), 1.0),
                  "unresolved": connectguard.port_state("no-such-host.invalid", 80, 1.0)}
    finally:
        listener.close()
    silent = probelib.listening("127.0.0.1", backlog=0)
    silent_port = silent.getsockname()[1]
    filler = socket.socket()
    filler.settimeout(1.0)
    try:
        filler.connect(("127.0.0.1", silent_port))
        states["silent"] = connectguard.port_state("127.0.0.1", silent_port, timeout=0.2)
    finally:
        filler.close()
        silent.close()
    return states


def retry_until_up() -> dict:
    """A service that starts listening 200 ms after the call: the loop's account of it."""
    port_holder = {"port": probelib.free_port()}

    def serve() -> None:
        time.sleep(0.2)
        server = probelib.listening("127.0.0.1", port=port_holder["port"])
        port_holder["server"] = server

    thread = threading.Thread(target=serve)
    thread.start()
    try:
        result = connectguard.retry(
            lambda: connectguard.dial("127.0.0.1", port_holder["port"], timeout=0.5),
            deadline_s=2.0)
    finally:
        thread.join()
        port_holder["server"].close()
    return {"attempts": result["attempts"], "waits": result["waits"],
            "elapsed_s": result["elapsed_s"],
            "last_error": type(result["error"]).__name__ if result["error"] else None}


def retry_expired() -> dict:
    number = probelib.free_port()
    result = connectguard.retry(
        lambda: connectguard.dial("127.0.0.1", number, timeout=0.5), deadline_s=0.3)
    return {"attempts": result["attempts"], "waits": result["waits"],
            "elapsed_s": result["elapsed_s"],
            "last_error": type(result["error"]).__name__,
            "reason": connectguard.explain(result["error"])}


def retry_silent() -> dict:
    server = probelib.listening("127.0.0.1", backlog=0)
    port = server.getsockname()[1]
    filler = socket.socket()
    filler.settimeout(1.0)
    filler.connect(("127.0.0.1", port))
    try:
        result = connectguard.retry(
            lambda: connectguard.dial("127.0.0.1", port, timeout=0.2), deadline_s=0.3)
        return {"attempts": result["attempts"], "waits": result["waits"],
                "last_error": type(result["error"]).__name__,
                "reason": connectguard.explain(result["error"])}
    finally:
        filler.close()
        server.close()


def main() -> None:
    arms = [
        probelib.once("explain_matrix", explain_matrix),
        probelib.once("dial_refused", dial_error),
        probelib.once("dial_any_mixed", dial_any_mixed),
        probelib.once("port_states", port_states),
        probelib.once("retry_until_up", retry_until_up),
        probelib.once("retry_expired", retry_expired),
        probelib.once("retry_silent", retry_silent),
    ]
    payload = probelib.record(
        "07_package",
        "the module's own answers on the conditions it names, including two retry loops",
        arms)
    path = probelib.write("07_package", payload)
    print("wrote", path)
    for arm in arms:
        print(f"{arm['label']:18s} {arm['runs'][0]}")


if __name__ == "__main__":
    main()
the deploy race and four client habits sandbox/08_repro.py
"""The deploy race: a service that starts listening 250 ms after the first attempt."""
from __future__ import annotations

import socket
import threading
import time

import probelib

import connectguard

DELAY_S = 0.25


def race_once() -> dict:
    port = probelib.free_port()

    def serve() -> None:
        time.sleep(DELAY_S)
        server = probelib.listening("127.0.0.1", port=port)
        holder["server"] = server

    holder: dict = {}
    thread = threading.Thread(target=serve)
    thread.start()
    try:
        first = probelib.connect("127.0.0.1", port, timeout=1.0)
        result = connectguard.retry(
            lambda: connectguard.dial("127.0.0.1", port, timeout=0.5), deadline_s=2.0)
        sock = result["socket"]
        if sock is not None:
            sock.close()
        return {"first_errno": first["errno"], "first_exception": first["exception"],
                "attempts": result["attempts"], "waits": result["waits"],
                "elapsed_s": result["elapsed_s"], "connected": sock is not None}
    finally:
        thread.join()
        if "server" in holder:
            holder["server"].close()


def fixed_wait_once() -> dict:
    """The other habit: sleep a constant, then dial once."""
    port = probelib.free_port()
    holder: dict = {}

    def serve() -> None:
        time.sleep(DELAY_S)
        holder["server"] = probelib.listening("127.0.0.1", port=port)

    thread = threading.Thread(target=serve)
    thread.start()
    try:
        time.sleep(1.0)
        answer = probelib.connect("127.0.0.1", port, timeout=1.0)
        return {"errno": answer["errno"], "connected": answer["ok"]}
    finally:
        thread.join()
        holder["server"].close()


def storm() -> dict:
    """A loop with no wait at all, for as long as the deadline a sane caller would spend."""
    number = probelib.free_port()
    started = time.monotonic()
    attempts = 0
    while time.monotonic() - started < 0.2:
        sock = socket.socket()
        try:
            sock.connect(("127.0.0.1", number))
        except OSError:
            attempts += 1
        finally:
            sock.close()
    return {"attempts": attempts, "seconds": round(time.monotonic() - started, 3),
            "per_attempt_us": round((time.monotonic() - started) / attempts * 1e6, 1)}


def main() -> None:
    arms = [
        probelib.repeat("startup_race", race_once, times=5),
        probelib.repeat("fixed_wait", fixed_wait_once, times=5),
        probelib.repeat("busy_loop", storm, times=5),
    ]
    payload = probelib.record(
        "08_repro",
        "the service listens 250 ms after the first dial; five runs of each client habit",
        arms, delay_s=DELAY_S, repeats=5)
    path = probelib.write("08_repro", payload)
    print("wrote", path)
    for arm in arms:
        print(arm["label"], arm["runs"])


if __name__ == "__main__":
    main()
the tree’s own counts sandbox/09_counts.py
"""The tree's own counts: what the body quotes about the package, its tests and the probes."""
from __future__ import annotations

import pathlib
import re
import subprocess
import sys

import probelib

HERE = pathlib.Path(__file__).resolve().parent.parent
PACKAGE = HERE / "connectguard"
TESTS = PACKAGE / "tests"
SANDBOX = HERE / "sandbox"
EXAMPLES = HERE / "examples"


def lines_of(paths: list[pathlib.Path]) -> int:
    return sum(len(path.read_text(encoding="utf-8").splitlines()) for path in paths)


def main() -> None:
    result = subprocess.run([sys.executable, "-m", "pytest", "connectguard/tests", "-q",
                             "-p", "no:cacheprovider", "-p", "no:warnings"],
                            cwd=str(HERE), capture_output=True, text=True)
    output = (result.stdout + result.stderr).strip()
    passed = int(match.group(1)) if (match := re.search(r"(\d+) passed", output)) else 0
    package_files = sorted(PACKAGE.glob("*.py"))
    test_files = sorted(TESTS.glob("*.py"))
    probe_files = sorted(SANDBOX.glob("*.py"))
    example_files = sorted(EXAMPLES.glob("*.py"))
    demo = subprocess.run([sys.executable, "examples/connect_demo.py"], cwd=str(HERE),
                          capture_output=True, text=True,
                          env={**__import__("os").environ, "PYTHONPATH": str(HERE)})
    notes = {
        "pytest_passed": passed,
        "example_output_lines": len(demo.stdout.strip().splitlines()),
        "example_rc": demo.returncode,
        "pytest_rc": result.returncode,
        "package_files": len(package_files),
        "package_lines": lines_of(package_files),
        "test_files": len(test_files),
        "test_lines": lines_of(test_files),
        "probe_files": len(probe_files),
        "probe_lines": lines_of(probe_files),
        "example_files": len(example_files),
        "example_file_lines": lines_of(example_files),
        "package_names": [path.name for path in package_files],
        "test_names": [path.name for path in test_files],
        "probe_names": [path.name for path in probe_files],
        "last_line": output.splitlines()[-1] if output else "",
    }
    payload = probelib.record("09_counts", "counts read from the files, and the suite's own run",
                              [probelib.once("counts", lambda: notes)], notes=notes)
    path = probelib.write("09_counts", payload)
    print("wrote", path)
    print(notes)


if __name__ == "__main__":
    main()
the four answers in one run examples/connect_demo.py
"""Seven lines from one run: what each state of a port looks like to a caller."""
from __future__ import annotations

import socket

from connectguard import advice, explain, port_state
from connectguard import backoff


def closed_port() -> int:
    sock = socket.socket()
    try:
        sock.bind(("127.0.0.1", 0))
        return sock.getsockname()[1]
    finally:
        sock.close()


def listener(backlog: int) -> socket.socket:
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(backlog)
    return server


def main() -> None:
    print("closed port:", port_state("127.0.0.1", closed_port(), timeout=1.0))
    open_server = listener(8)
    print("open port:", port_state("127.0.0.1", open_server.getsockname()[1], timeout=1.0))
    open_server.close()
    full_server = listener(0)
    filler = socket.socket()
    filler.settimeout(1.0)
    filler.connect(("127.0.0.1", full_server.getsockname()[1]))
    print("full queue:", port_state("127.0.0.1", full_server.getsockname()[1], timeout=0.2))
    filler.close()
    full_server.close()
    print("unresolved name:", port_state("no-such-host.invalid", 80, timeout=1.0))
    print("a reset is:", explain(ConnectionRefusedError(111, "Connection refused")))
    print("waits:", " ".join(f"{wait:g}" for wait in backoff.delays(5)))
    print("advice:", advice(explain(ConnectionRefusedError(111, "Connection refused"))))


if __name__ == "__main__":
    main()

Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.