TL;DR: One Port, One Owner, One Timer
EADDRINUSE: [Errno 98] Address already in useis not one situation: 5 of the 12 bind conditions here returned it, from a live listener in three shapes, a wildcard address, and one lone TIME_WAIT entry.- A live owner does not come back by waiting. The TIME_WAIT timer is fixed at 60 s, and a plain rebind needed 602, 122 or 62 polls for it depending on how often it looked; the release those polls bracket is about 60.3 s after the entry, not the nominal 60 s, while the port bound at once when
SO_REUSEADDRwas set on the socket that owned it. - The flag belongs to the socket that left the entry: 3 of the 7 reuse arms bound, and every failure had at least one of the two sockets without the flag.
- Two listeners on one port need
SO_REUSEPORTon both; with it, no listener took fewer than 86 or more than 114 of the 200 connections in any of five rounds, so no worker owns a session.
Scope. One Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, loopback only, 5 repeats per arm. Nothing was tuned; section 9 is read from /proc. This host has no IPv6 (AF_INET6 is refused with errno 97), so every IPv6 statement below is a documented kernel rule.
Fix It First: Eight Changes, Matched to Your Log Line
Find the line in your log, stop at the first row that matches, and make that change. The owner comes first; the flag is a line of code; waiting is a decision, and only a leftover entry is worth it.
| What the log shows | Change to make (and what measured it) |
|---|---|
Address already in use at startup | Look for a live process first (ss -ltnp, or the table in section 8); only then a flag or a wait – 5 of 12 conditions returned it (section 1) |
| Busy for a minute after every deploy | Set SO_REUSEADDR on the socket that will own the port, before its first bind, instead of sleeping in the start script – 602, 122 or 62 polls against a flagged rebind that bound at once (sections 3 and 5) |
| A specific address fails while a wildcard listener runs | Bind the address the owner bound, or stop the wildcard listener – errno 98 against it, while another loopback address bound (section 1) |
| Two workers cannot share one port | Set SO_REUSEPORT on every listener that should share it – errno 98 against a plain listener (section 4) |
Cannot assign requested address | Check that the address belongs to this host; no wait clears it – errno 99 for a foreign address (section 6) |
Permission denied below port 1,024 | Bind at or above the unprivileged start, or grant the capability – errno 13 at the privileged port (section 6) |
| A fixed source port cannot connect again | Set SO_REUSEADDR on the socket that used the port before it closed, or stop pinning the source port – errno 98 without the flag, a connect that worked with it on loopback (section 3) |
| TIME_WAIT counts climb on the wrong side | Close from the side whose port pool is larger: the side that closes first keeps the entry – client 1 against 0 (section 2) |
1. Twelve Binds, One Number
bind() returns a number, and that number is nearly all a start script prints. Probe 02 runs 12 conditions – ten on a fresh port, two on a fixed port or address – from a live listener to a foreign address, and table 2 is the whole list.
| Condition the bind met | Kernel answer | What decided it |
|---|---|---|
| Another listener on the address | errno 98 | the port has an owner in LISTEN |
The same, with SO_REUSEADDR on the new socket | errno 98 | the flag skips TIME_WAIT, not a live owner |
Two listeners, both with SO_REUSEPORT | bound in 1.0 µs to 4.0 µs | the flag lets the second listener join |
SO_REUSEPORT against a listener without it | errno 98 | every listener must join the group |
| Wildcard listener, bind to one address | errno 98 | the wildcard covers every address |
| Specific listener, bind to another loopback address | bound | a specific address is only itself |
| TCP listener, UDP socket on the same port | bound | TCP and UDP keep separate tables |
| Listener closed without accepting | bound | nothing was left to own the port |
| Server closed first, then the listener | errno 98 | one TIME_WAIT entry on the port |
| The same entry, flag set on the new socket | bound in 10.0 µs to 13.0 µs | the entry is skipped |
| Port below the unprivileged start | errno 13 | no capability to bind it |
| An address this host does not own | errno 99 | the address is not local |
Three rows break a habit. SO_REUSEADDR does not let a new socket listen beside a live listener – it skips a TIME_WAIT entry, and a socket in LISTEN is not one. A second listener needs SO_REUSEPORT on both, which is why a manager that flags new workers but inherits an unflagged parent still fails. And the last two rows send people looking for a process that is not there: errno 13 is a permission denial, errno 99 a missing address, and retrying either turns one line into a crash loop.
The cause this table cannot show. Every condition above starts from an idle host, which is why the table models a laptop badly. The most common errno 98 in practice is a previous process that never exited: a uvicorn --reload whose reloader left a child, a gunicorn master with one worker alive, a container restarted under its process. Those already set SO_REUSEADDR, so the owner is a live socket: stop it or bind another port.
The usual tool is ss -ltnp. It is installed here and its table worked, but its process column could not be read, so no figure here comes from it – and that is the lesson for container readers: when -p cannot see across the namespace, the table in section 8 still shows the socket and its state.
One owner hides in plain sight on a dual-stack host: an IPv6 socket bound to :: with net.ipv6.bindv6only at 0 also occupies the IPv4 port, so a bind to 0.0.0.0 returns errno 98 while /proc/net/tcp shows nothing (section 8).
2. Who Owns the Port
A closed connection leaves an entry in the kernel’s table for a while, and who keeps it is decided by who sends the first FIN. Probe 06 ends one connection three ways and reads both local ports after both ends closed.
| How the connection ended | TIME_WAIT on the client port | TIME_WAIT on the server port |
|---|---|---|
| Client closed first | 1 | 0 |
| Server closed first | 0 | 1 |
Client reset with SO_LINGER 0 | 0 | 0 |
That rule decides which port pool a service exhausts. A server that closes idle connections keeps their entries on its listening port, where they cost little. A client that closes first keeps them on its ephemeral ports, one entry each from 28,232 – so a proxy that closes its own outbound calls pays on purpose. A reset with SO_LINGER 0 leaves no entry and looks healthier, while the peer sees a reset instead of a clean end.
3. The Flag Belongs to the Socket That Left
SO_REUSEADDR is not a switch on the socket being opened. It is a statement about the socket already gone: the kernel holds it in TIME_WAIT with whatever flags its owner set, and a new bind consults them. Probe 04 arranges one entry seven ways; 3 of the 7 arms bound.
| The socket that used the port | What the new socket asked for | Bind | Connect after |
|---|---|---|---|
| Server-side close, listener set the flag | SO_REUSEADDR | bound | not tried |
| Server-side close, listener set the flag | nothing | errno 98 | not tried |
| Client-side close, client set no flag | nothing | errno 98 | not tried |
| Client-side close, client set no flag | SO_REUSEADDR | errno 98 | not tried |
| Client-side close, client set the flag | SO_REUSEADDR | bound | ok |
| Server-side close, listener set no flag | SO_REUSEADDR | errno 98 | not tried |
| Client-side close, no fixed port wanted | nothing | bound by connect | ok |
Row four costs an afternoon: a client pins its source port for an allowlist, closes first, and the next attempt returns errno 98 although the new socket asks for the flag, because the entry says the old owner did not. Row five is the same code with the flag set before the first bind, and it connected. Row six closes the loop: a listener that never set the flag leaves entries nothing can skip, so the fix belongs above the first bind.
Row five carries a condition. This host runs tcp_tw_reuse at 2, which reuses a TIME_WAIT source port for an outbound connection on loopback only, and the arm connected to 127.0.0.1. The setting was read, not varied: with it off the connect would fail, and toward a remote address the value 2 does not apply – so the row means “loopback, this setting”, not a promise for a pinned source port to a remote peer.
4. Two Listeners, One Port
SO_REUSEPORT lets several sockets listen on one port, and the kernel picks which accepts each connection. Probe 05 opens two and makes 200 connections one at a time, five rounds.
| Round | First listener accepted | Second listener accepted |
|---|---|---|
| 1 | 93 | 107 |
| 2 | 86 | 114 |
| 3 | 99 | 101 |
| 4 | 103 | 97 |
| 5 | 108 | 92 |
The split is a hash of the four-tuple: 86 to 108 for the first listener, 92 to 114 for the second – close to half, never exact. A worker cannot count on receiving a reconnecting client it served a moment ago, so session state in one process needs a shared store or a router.
Two kernel rules were not measured here. Only sockets with the same effective UID may join one SO_REUSEPORT group, so another user’s process cannot take a share. And a worker that leaves the group drops the requests in its accept queue: the kernel can migrate them with net.ipv4.tcp_migrate_req, which this host reports at 0 – its default – so a runbook drains before closing instead of counting on that hand-off. Both failures return errno 98 like a live owner.
5. The Sixty Seconds, Measured at Three Intervals
Probe 03 leaves one TIME_WAIT entry on each of fifteen ports and attempts a plain bind until it succeeds – every 0.1 s on five ports, every 0.5 s on five, every 1.0 s on the last five. All fifteen arms run at once, so no arm waits behind another.
| Polling interval | Arms | Wait (median) | Fastest to slowest | Bind attempts |
|---|---|---|---|---|
| 0.1 s | 5 | 60,386.1 ms | 60,384.8 ms to 60,387.0 ms | 602 |
| 0.5 s | 5 | 60,540.4 ms | 60,539.7 ms to 60,543.0 ms | 122 |
| 1.0 s | 5 | 61,030.1 ms | 61,027.3 ms to 61,031.9 ms | 62 |
Read the attempt column first: 602, 122 and 62 binds are one per interval, so the loop is the timer plus the step it is checked on. That accounts for the step, not for the rest of the number. At 0.1 s the count reaches its last attempt at 60,100.0 ms, while the bind that succeeded came 60,386.1 ms after the entry – 286.1 ms later. Part of that gap is the loop itself, one sleep and one bind per attempt, neither of them timed on its own. Part of it may be the kernel’s.
The three arms agree on where the entry went even if they cannot split that gap: the bind one step before the successful one failed, so the release sits inside a window one 0.1 s step wide that ends at 60,386.1 ms – about 60.3 s at the window’s middle, a third of a second past the compiled timer rather than at it. The 0.5 s and 1.0 s arms bracket the same release and sit further out only because their next beat is coarser. Timer-wheel rounding is the usual explanation for a fixed timer letting go a fraction late; this experiment reads the timer through binds alone and did not measure the wheel.
Two gaps describe those beats, and they are not the same number. The medians of the finest and the coarsest arm differ by 644.0 ms (61,030.1 ms against 60,386.1 ms); the full spread across all fifteen arms, fastest to slowest, is 647.1 ms, from 60,384.8 ms to 61,031.9 ms. Neither is a timer that drifts: five arms at one interval agree within a few milliseconds, and the finer beat prints a smaller number because its next poll comes sooner, not because its timer is shorter.
The timer is not tunable: Linux enters the entry with a timeout compiled into the kernel – TCP_TIMEWAIT_LEN, 60 seconds in include/net/tcp.h – and no /proc/sys file changes it. tcp_fin_timeout, which advice keeps reaching for, governs FIN_WAIT_2 instead, where a half-closed connection waits for the peer’s FIN; this host reports 60 there as well, and two equal values side by side are why the myth survives. The waiter in the appendix sets no flag by default: one that did would skip the entry it was waiting for.
6. Three Errors, and Only One Is a Conflict
Probe 07 produces five failures from this kernel – four by a real bind, one by writing into a pipe whose reader has gone. Two of the bind arms share errno 98 and differ only in the owner the table reports: a live listener in one, a lone TIME_WAIT entry in the other.
| What produced it here | Classified as | Owner in the table | Wait | Retries |
|---|---|---|---|---|
| A bind beside a live listener | in_use | LISTEN 1 | 0 s | 0 |
| A bind whose only owner is one TIME_WAIT entry | in_use | TIME_WAIT 1 | 60 s | 0 |
| A bind to an address this host does not own | not_available | no entry | 0 s | 1 |
| A bind below the unprivileged start | permission | no entry | 0 s | 0 |
| A write into a pipe with no reader | unrelated | not a bind | 0 s | 0 |
The two errno 98 rows differ only in the owner, and that is the whole fix: waiting on a live listener is the one action guaranteed to fail, and a lone TIME_WAIT entry is the only row here worth a timer. A half-closed socket is an owner too, and its end is not this page’s clock: an orphaned FIN_WAIT_2 is reaped after tcp_fin_timeout seconds, which this host reports at the same 60 s as the entry timer (table 8), and a LAST_ACK socket whose peer has gone ends on the retransmission timeout – neither of which says how much of the time is left. TIME_WAIT is the one state with a length the kernel fixes for every entry and never varies, so it is the only one the classifier gives a wait budget.
The two non-conflicts are commonly reported as a collision. EADDRNOTAVAIL means the address is not local – a typo, an interface that went away – and no wait makes it local; the same number on an outbound connect means no free source port in 32,768 to 60,999, which is 28,232 ports this page did not exhaust. EACCES means the port is below 1,024, refused before any table exists.
"""Errno to Fault: what a bind failure means, what to do about it, and how long to wait.
A bind failure is one of three things on this platform - another socket owns the port, the address
cannot be used from here, or the port is below the unprivileged start - and the number alone is not
enough to tell them apart from a mistyped address. ``TABLE`` names the three, ``classify`` follows a
wrapped exception to the first ``OSError`` that carries one of them, and anything else comes back as
unrelated rather than being quietly retried.
The wait is a second question. ``advise`` answers it with the kernel's table in hand: a socket
that is still listening, connected or closing is held by a process, not by the timer this page
waits out, and only a port whose owners are all TIME_WAIT is worth waiting for. Without the table
it returns the number's generic advice and promises no wait.
"""
from __future__ import annotations
import errno
from dataclasses import dataclass, replace
from enum import Enum
TIME_WAIT_S = 60.0
LIVE_STATES = ("LISTEN", "SYN_SENT", "SYN_RECV", "ESTABLISHED")
CLOSING_STATES = ("FIN_WAIT1", "FIN_WAIT2", "CLOSE", "CLOSE_WAIT", "CLOSING", "LAST_ACK")
class Kind(Enum):
"""The three ways a bind fails, and the group everything else falls into."""
IN_USE = "in_use"
NOT_AVAILABLE = "not_available"
PERMISSION = "permission"
UNRELATED = "unrelated"
@dataclass(frozen=True)
class Fault:
"""One errno, what it means for a bind, and the one action it is worth.
``wait_s`` and ``retry_budget`` are never both set: a fault asks for a wait or for a retry,
and a row that asked for both would tell a caller to sleep through a conflict it could not
outlast.
"""
number: int
name: str
kind: Kind
remedy: str
retry_budget: int
wait_s: float = 0.0
TABLE = {
errno.EADDRINUSE: Fault(
errno.EADDRINUSE, "EADDRINUSE", Kind.IN_USE,
"find the socket that owns the port before deciding anything else", 0),
errno.EADDRNOTAVAIL: Fault(
errno.EADDRNOTAVAIL, "EADDRNOTAVAIL", Kind.NOT_AVAILABLE,
"check that the address belongs to this host; for an outbound connect, retry once from "
"another source port", 1, 0.0),
errno.EACCES: Fault(
errno.EACCES, "EACCES", Kind.PERMISSION,
"bind a port at or above the unprivileged start, or grant the process "
"CAP_NET_BIND_SERVICE", 0, 0.0),
}
def unwrap(exc: BaseException) -> BaseException:
"""The first exception in the cause chain that is an ``OSError``, or the one given."""
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
seen.add(id(current))
if isinstance(current, OSError):
return current
current = current.__cause__ or current.__context__
return exc
def classify(exc: BaseException) -> Fault:
"""Map an exception to a row of ``TABLE``, or to an unrelated fault that keeps its number."""
error = unwrap(exc)
number = int(getattr(error, "errno", 0) or 0)
if number in TABLE:
return TABLE[number]
return Fault(number, errno.errorcode.get(number, "unknown"), Kind.UNRELATED,
"not a bind conflict: read the full traceback before acting", 0, 0.0)
def advise(exc: BaseException, states: dict[str, int] | None = None) -> Fault:
"""The fault, with its wait corrected by who is still holding the port.
``states`` is what the kernel's table reports for the port (``states_for_port``): a listener,
a connection or a socket that is still closing means the answer is to stop that owner,
TIME_WAIT alone means the answer is one timer, and no entry at all means the bind is worth
one more attempt.
"""
fault = classify(exc)
if fault.kind is not Kind.IN_USE or states is None:
return fault
if any(states.get(state) for state in LIVE_STATES):
return replace(fault, retry_budget=0, wait_s=0.0,
remedy="a live socket owns the port: stop that process, or bind another "
"port; no timer clears it")
if any(states.get(state) for state in CLOSING_STATES):
return replace(fault, retry_budget=0, wait_s=0.0,
remedy="a closing or half-closed socket owns the port: stop that process, "
"or bind another port; only TIME_WAIT ends on a clock this wait keeps")
if states.get("TIME_WAIT"):
return replace(fault, retry_budget=0, wait_s=TIME_WAIT_S,
remedy="only TIME_WAIT entries remain: wait one timer, or set SO_REUSEADDR "
"on the socket that owns the entry before its first bind")
return replace(fault, retry_budget=1, wait_s=0.0,
remedy="the table shows no owner now: retry the bind once")
That block is the decision half of one file and runs alone – standard library only – so it drops into a service. The appendix prints the file whole, with the two helpers this excerpt leaves out.
7. The Restart Runbook
Everything above collapses into an order of operations a deploy script can follow without knowing which case it is in. The order matters: the two safe answers – start now with the flag, or wait out an entry – are decided before the bind, not after it fails.
- Read the number. If it is not a bind error, stop and read the traceback.
- Read the table for the port. A live socket means the old process has not exited; TIME_WAIT alone means it has and only the entry is left.
- Set
SO_REUSEADDRon the new listener before its first bind, in every process that will ever own the port, not only the one restarting now. - Set
SO_REUSEPORTonly if several processes should accept on one port; on one process alone it turns a shared port into errno 98. - If the owner is live and you cannot stop it, bind another port. No flag skips a socket in LISTEN.
- If the owner is a leftover entry, wait one timer or add the flag; the interval decides how long the wait looks. Log one line per failure with address, number, owner and action.
8. Reading the Kernel’s Tables
The table is a text file, one line per socket, and it answers what a log cannot: which local port is still held, and in which state. The parser below reads /proc/net/tcp for IPv4 and /proc/net/tcp6 for IPv6, keeps only socket lines, and counts them per port; a host without IPv6 has no second file and the reader skips it.
"""Reading the kernel's own socket tables: who holds a port, and in which state.
``/proc/net/tcp`` is one line per IPv4 socket, ``/proc/net/tcp6`` the same for IPv6, with the local
port in hex and the state in a two-byte code. Both are read here without a dependency, because a
listener on ``::`` owns the IPv4 port too and an owner that only one file lists is the owner a
reader misses.
"""
from __future__ import annotations
import pathlib
TABLE_PATHS = (pathlib.Path("/proc/net/tcp"), pathlib.Path("/proc/net/tcp6"))
STATE_NAMES = {
"01": "ESTABLISHED",
"02": "SYN_SENT",
"03": "SYN_RECV",
"04": "FIN_WAIT1",
"05": "FIN_WAIT2",
"06": "TIME_WAIT",
"07": "CLOSE",
"08": "CLOSE_WAIT",
"09": "LAST_ACK",
"0A": "LISTEN",
"0B": "CLOSING",
}
def local_port(line: str) -> int | None:
"""The local port of one table line, or None when the line is not a socket."""
fields = line.split()
if len(fields) < 4 or not fields[0].rstrip(":").isdigit():
return None
_, _, port = fields[1].partition(":")
if not port:
return None
try:
return int(port, 16)
except ValueError:
return None
def state_code(line: str) -> str | None:
"""The two-byte state of one table line, or None when it is not one this table names."""
fields = line.split()
if len(fields) < 4 or fields[3] not in STATE_NAMES:
return None
return fields[3]
def parse(text: str) -> list[dict]:
"""Every socket in a table file, as local port and state name."""
entries: list[dict] = []
for line in (text or "").splitlines()[1:]:
port = local_port(line)
code = state_code(line)
if port is None or code is None:
continue
entries.append({"local_port": port, "state": STATE_NAMES[code]})
return entries
def table_text(paths: tuple[pathlib.Path, ...] = TABLE_PATHS) -> str:
"""Both kernel tables as one text; a host that has no IPv6 simply has no second file."""
texts: list[str] = []
for path in paths:
try:
texts.append(path.read_text(encoding="utf-8"))
except OSError:
continue
return "\n".join(texts)
def states_for_port(port: int, text: str | None = None) -> dict[str, int]:
"""How many sockets on one local port are in each state, as the kernel reports them."""
table = table_text() if text is None else text
counts: dict[str, int] = {}
for entry in parse(table):
if entry["local_port"] == port:
counts[entry["state"]] = counts.get(entry["state"], 0) + 1
return counts
The port is hexadecimal, which is why a search for the decimal port finds nothing. The state is a two-byte code: listening is 0A, established 01, and this page’s entry 06. The second file matters because a listener on :: is invisible in /proc/net/tcp and, with net.ipv6.bindv6only at its default, also occupies the IPv4 port; this host has no IPv6, so that branch is tested on a recorded line.
The one line to log
A failure log is read by someone who did not write the code, at the worst possible moment. The line below carries address, number, name, cause, the owner’s verdict, wait, retries and remedy in one sentence.
"""One log line for a failed bind, with the fields an on-call reader needs.
A traceback says where the code was. It does not say which port, which of the three causes, or
whether waiting would help - so the line this module prints carries those instead, and the number
keeps its own name.
"""
from __future__ import annotations
from .errors import advise
def describe_bind_failure(exc: BaseException, address: tuple[str, int],
states: dict[str, int] | None = None) -> str:
"""One line: address, number, name, cause, wait, retries and the remedy.
Pass ``states`` from the kernel's table and the wait becomes the owner's answer; without it
the line keeps the number's generic advice and claims no wait.
"""
fault = advise(exc, states)
host, port = address
return (f"bind {host}:{port} failed: {fault.name} ({fault.number}) {fault.kind.value}; "
f"wait {fault.wait_s:g} s, retries {fault.retry_budget}; {fault.remedy}")
9. What Not to Change
Every setting here was read from /proc and left alone. The first row names the setting the errno 98 advice reaches for most, and it does not govern the timer in section 5.
| Setting | Value on this host | What it decides | Why not to touch it for this error |
|---|---|---|---|
tcp_fin_timeout | 60 | how long an orphaned FIN_WAIT_2 socket waits for the peer’s FIN | it does not touch TIME_WAIT: lowering it reaps half-closed sockets sooner |
tcp_max_tw_buckets | 4,096 | how many entries the kernel keeps at once | past the ceiling the kernel destroys entries and logs it; the conflict stays |
tcp_tw_reuse | 2 | 0 off, 1 everywhere, 2 loopback only, which is what this host runs | it applies to outbound connects and never to a listener |
ip_local_port_range | 32,768 to 60,999 | 28,232 source ports for outbound sockets | widening it buys headroom and takes ports from everything else |
ip_unprivileged_port_start | 1,024 | the lowest port a user may bind | lowering it removes the boundary that produced errno 13, for every process |
The habit fits one sentence: set SO_REUSEADDR before the bind, read the owner before deciding to wait, and let the kernel’s table rather than the application’s log say which case you are in. Restraint is the fourth – nothing here was tuned – and the one condition that needed time needed exactly one timer. Treat the numbers as one host’s measurement with a date.
Frequently asked questions
Why does my service wait a minute before it can bind after a restart?
Because the port still has an entry owned by the process that just exited. The timer is fixed at 60 s; a plain bind polled every 0.1 s needed 602 attempts here, and 122 at 0.5 s, so the millisecond figure is the loop’s length, not the timer’s resolution. The same port bound at once where SO_REUSEADDR was set on the socket that owned it, and tcp_fin_timeout does not shorten this timer.
Does SO_REUSEADDR let two workers listen on one port?
No. A second listener with the flag returned errno 98, like a plain second bind. Two listeners need SO_REUSEPORT on both, and in five rounds neither took under 86 or over 114 of the 200 connections.
I set the flag on the new socket and it still fails. Why?
The flag records what the socket that left asked for, not a permission for the one arriving. A client that closed first without it left an entry no newcomer can skip, and the retry returned errno 98 in every repeat. Set it before the first bind.
A previous process is still running. Is the entry permanent?
No, but a live process will not release the port for any timer. A socket in LISTEN or ESTABLISHED means the old owner is there: stop it. Once it is gone the entry outlives it for one timer, on the side that closed first – 1 entry there against 0 on the other; a reset leaves 0 on either side.
Should I catch errno 98 and retry in a loop?
No. Each row of the classifier asks for one action, and only a lone TIME_WAIT entry is worth waiting for; a live listener, a foreign address and a privileged port come back unchanged. The total retry budget across the bind rows is 1, and it belongs to the client that can pick another source port.
Take the next step
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
Appendix: Every File This Page Quotes
The probes and the package are printed in full, so every number above can be checked against the code that produced it. The tree is the one that ran; the run order reproduces it from an empty directory, and every fold is a character-for-character copy of its file.
Folder structure
post34/
sandbox/
probe.py a reserved port, one bind attempt, repeats, the JSON writer
01_conditions.py host, interpreter, IPv6 and kernel settings read, not changed
02_bind.py twelve bind conditions, ten fresh ports
03_timewait.py fifteen arms, three polling intervals
04_reuse.py seven arms around one TIME_WAIT entry
05_reuseport.py two listeners, one port, two hundred connections
06_tw_owner.py which side owns the entry, three endings
07_policy.py the classifier and the owner's verdict, on live failures
08_tests.py pytest, and the tree's own counts
module/
portguard/
__init__.py what a service imports
errors.py errno to Fault, with the owner's verdict
reuse.py the two flags, chosen by role
table.py both kernel socket tables, read per port
wait.py a wait with an interval and a result
report.py one log line
tests/
conftest.py a free port and a held port
test_errors.py classification, the wait, and the one-action rule
test_reuse.py the flags, and a failed bind that closes its socket
test_table.py hex ports, state codes, an IPv6 line, a missing file
test_wait.py a free port now, a held port until the timeout, a plain bind by default
results/ one JSON per probe, written by it
Run order
The probes need only the standard library; the two that read the kernel’s table add the package’s own directory to the path themselves. 08_tests.py needs pytest, and pyflakes is only for the static check.
$ python3 -m pip install pytest pyflakes # optional: 08_tests.py and the static check $ cd sandbox $ python3 01_conditions.py # the settings in section 9 $ python3 02_bind.py # table 2 $ python3 03_timewait.py # table 6, about one minute $ python3 04_reuse.py # table 4 $ python3 05_reuseport.py # table 5 $ python3 06_tw_owner.py # table 3 $ python3 07_policy.py # table 7 $ python3 08_tests.py # pytest, passed count $ cd ../module && python3 -m pytest portguard/tests -q
A reserved port, one bind attempt with named options, and the JSON writer. probe.py
"""Shared parts of the probes: a loopback pair, repeats, and one JSON file per probe.
Every probe writes what it observed, not what it expected. ``repeat`` runs the same call five
times and keeps each observation, so a figure in the article can be reported as a median with its
range instead of a single run that happened to be first. ``reserve`` hands out a port that was
free a moment ago, so two arms never measure each other's leftovers.
"""
from __future__ import annotations
import json
import pathlib
import socket
import statistics
import time
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
REPEATS = 5
def save(number: str, name: str, payload: dict) -> pathlib.Path:
"""Write one probe's record and print where it went."""
RESULTS.mkdir(parents=True, exist_ok=True)
path = RESULTS / f"{number}_{name}.json"
path.write_text(json.dumps(payload, ensure_ascii=False, indent=1, sort_keys=True) + "\n",
encoding="utf-8")
print("wrote", path.name)
return path
def repeat(call, times: int = REPEATS) -> list:
"""Call the same measurement ``times`` times and keep every result."""
return [call() for _ in range(times)]
def summary(values: list[float]) -> dict:
"""The three figures a five-run arm can honestly report."""
return {"min": min(values), "median": statistics.median(values), "max": max(values)}
def free_port(host: str = "127.0.0.1") -> int:
"""A port the kernel called free a moment ago, closed before it is used."""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, 0))
port = sock.getsockname()[1]
sock.close()
time.sleep(0.01)
return port
def listen(port: int, host: str = "127.0.0.1", reuse_addr: bool = True,
reuse_port: bool = False, backlog: int = 5) -> socket.socket:
"""A listening socket with the flags named, so each arm controls its own options."""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 if reuse_addr else 0)
if reuse_port:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((host, port))
sock.listen(backlog)
return sock
def attempt_bind(port: int, host: str = "127.0.0.1", reuse_addr: bool = False,
reuse_port: bool = False) -> dict:
"""Try one bind and record the number and the time it took, success or not."""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 if reuse_addr else 0)
if reuse_port:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
started = time.perf_counter()
try:
sock.bind((host, port))
except OSError as exc:
return {"bound": False, "number": int(exc.errno or 0), "error": type(exc).__name__,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3)}
finally:
elapsed = round((time.perf_counter() - started) * 1000, 3)
try:
sock.close()
except OSError:
pass
return {"bound": True, "number": 0, "error": None, "elapsed_ms": elapsed}
def attempt_bind_strict(port: int, host: str = "127.0.0.1") -> None:
"""One bind with no options, raising whatever the kernel says instead of reporting it."""
sock = socket.socket()
try:
sock.bind((host, port))
finally:
sock.close()
def close_quietly(sock: socket.socket) -> None:
"""Close without letting a teardown error become the measurement."""
try:
sock.close()
except OSError:
pass
Host, interpreter, IPv6 availability and the kernel settings this page reads. 01_conditions.py
"""Probe 01: the host, the interpreter, and the kernel settings these runs depend on.
Nothing here is changed. Each value is read from the running kernel through ``/proc`` or from the
socket module's own constants, so the article can say which numbers were measured and which were
read out of a file instead of guessing either. The last two facts say what this host cannot do:
whether an IPv6 socket can be opened here, and whether ``ss`` can name a process owner.
"""
from __future__ import annotations
import os
import pathlib
import platform
import shutil
import socket
import subprocess
import probe
def read(path: str) -> str:
return pathlib.Path(path).read_text(encoding="utf-8").strip()
def kernel_setting(name: str) -> int:
return int(read(f"/proc/sys/net/ipv4/{name}"))
def optional_setting(name: str) -> tuple[bool, int | None]:
"""A setting newer kernels carry and older ones do not: present, and its value if so."""
path = pathlib.Path(f"/proc/sys/net/ipv4/{name}")
if not path.exists():
return False, None
return True, int(path.read_text(encoding="utf-8").strip())
def ipv6() -> dict:
"""Whether an IPv6 socket can be opened on this host, and the errno if it cannot."""
try:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
except OSError as exc:
return {"ipv6": False, "ipv6_errno": int(exc.errno or 0)}
sock.close()
return {"ipv6": True, "ipv6_errno": 0}
def listener_command() -> dict:
"""What the host's own listener command can report here: the table, and the process owner."""
path = shutil.which("ss")
if path is None:
return {"ss": "absent", "ss_error": "not installed"}
try:
result = subprocess.run([path, "-ltnp"], capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError) as exc:
return {"ss": "present", "ss_error": type(exc).__name__}
lines = (result.stderr or "").strip().splitlines()
return {"ss": "present", "ss_error": lines[0][:80] if lines else "",
"ss_returncode": result.returncode}
def main() -> None:
low, high = (int(part) for part in read("/proc/sys/net/ipv4/ip_local_port_range").split())
facts = {
"kernel": platform.release(),
"python": platform.python_version(),
"cpu_count": os.cpu_count(),
"repeats": probe.REPEATS,
"ip_local_port_low": low,
"ip_local_port_high": high,
"ephemeral_ports": high - low + 1,
"tcp_fin_timeout": kernel_setting("tcp_fin_timeout"),
"tcp_max_tw_buckets": kernel_setting("tcp_max_tw_buckets"),
"tcp_tw_reuse": kernel_setting("tcp_tw_reuse"),
"tcp_migrate_req": optional_setting("tcp_migrate_req")[1],
"tcp_migrate_req_present": optional_setting("tcp_migrate_req")[0],
"somaxconn": int(read("/proc/sys/net/core/somaxconn")),
"unprivileged_port_start": kernel_setting("ip_unprivileged_port_start"),
"so_reuseaddr": int(socket.SO_REUSEADDR),
"so_reuseport": int(socket.SO_REUSEPORT),
"so_linger": int(socket.SO_LINGER),
"localhost_count": sum(1 for name in ("127.0.0.1", "127.0.0.2") if _is_local(name)),
"proc_net_tcp": read("/proc/net/tcp").splitlines()[0][:30],
"proc_net_tcp6": pathlib.Path("/proc/net/tcp6").exists(),
**ipv6(),
**listener_command(),
}
print("facts:", facts)
probe.save("01", "conditions", {"facts": facts})
def _is_local(address: str) -> bool:
sock = socket.socket()
try:
sock.bind((address, 0))
return True
except OSError:
return False
finally:
sock.close()
if __name__ == "__main__":
main()
Twelve bind conditions, ten of them on a port the previous arm released. 02_bind.py
"""Probe 02: twelve conditions under which a bind is attempted, and the number each returns.
Ten arms take a port the kernel called free a moment ago and release it before the next arm runs;
the privileged port and the foreign address are fixed, because their condition is the port or the
address itself. Every arm returns the number the kernel gave (zero for a bind that succeeded) and
how long the call took, so the table can separate "another socket is listening" from "the port is
free again".
"""
from __future__ import annotations
import socket
import time
import probe
def second_listener_plain() -> dict:
port = probe.free_port()
first = probe.listen(port)
try:
return probe.attempt_bind(port)
finally:
probe.close_quietly(first)
def second_listener_reuseaddr() -> dict:
port = probe.free_port()
first = probe.listen(port)
try:
return probe.attempt_bind(port, reuse_addr=True)
finally:
probe.close_quietly(first)
def second_listener_reuseport() -> dict:
port = probe.free_port()
first = probe.listen(port, reuse_port=True)
try:
return probe.attempt_bind(port, reuse_addr=True, reuse_port=True)
finally:
probe.close_quietly(first)
def reuseport_against_plain() -> dict:
port = probe.free_port()
first = probe.listen(port)
try:
return probe.attempt_bind(port, reuse_addr=True, reuse_port=True)
finally:
probe.close_quietly(first)
def wildcard_vs_specific() -> dict:
port = probe.free_port()
first = probe.listen(port, host="0.0.0.0")
try:
return probe.attempt_bind(port, host="127.0.0.1")
finally:
probe.close_quietly(first)
def specific_vs_specific() -> dict:
port = probe.free_port()
first = probe.listen(port)
try:
return probe.attempt_bind(port, host="127.0.0.2")
finally:
probe.close_quietly(first)
def udp_same_port() -> dict:
port = probe.free_port()
first = probe.listen(port)
other = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
started = time.perf_counter()
try:
other.bind(("127.0.0.1", port))
return {"bound": True, "number": 0, "error": None,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3)}
except OSError as exc:
return {"bound": False, "number": int(exc.errno or 0), "error": type(exc).__name__,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3)}
finally:
probe.close_quietly(other)
probe.close_quietly(first)
def after_listener_close() -> dict:
port = probe.free_port()
first = probe.listen(port)
probe.close_quietly(first)
time.sleep(0.01)
return probe.attempt_bind(port)
def after_server_close_plain() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close() # the server closes first: it owns the TIME_WAIT
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
time.sleep(0.01)
return probe.attempt_bind(port)
def after_server_close_reuseaddr() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
time.sleep(0.01)
return probe.attempt_bind(port, reuse_addr=True)
def privileged_port() -> dict:
return probe.attempt_bind(80)
def foreign_address() -> dict:
return probe.attempt_bind(0, host="10.255.255.1")
ARMS = {
"second_listener_plain": second_listener_plain,
"second_listener_reuseaddr": second_listener_reuseaddr,
"second_listener_reuseport": second_listener_reuseport,
"reuseport_against_plain": reuseport_against_plain,
"wildcard_vs_specific": wildcard_vs_specific,
"specific_vs_specific": specific_vs_specific,
"udp_same_port": udp_same_port,
"after_listener_close": after_listener_close,
"after_server_close_plain": after_server_close_plain,
"after_server_close_reuseaddr": after_server_close_reuseaddr,
"privileged_port": privileged_port,
"foreign_address": foreign_address,
}
def main() -> None:
arms = []
for name, call in ARMS.items():
observations = probe.repeat(call)
first = observations[0]
identical = all(observation["number"] == first["number"] for observation in observations)
elapsed = [observation["elapsed_ms"] for observation in observations]
arms.append({"name": name, "repeats": len(observations), "identical": identical,
"number": first["number"], "bound": first["bound"],
"error": first["error"], "elapsed_ms": first["elapsed_ms"],
"elapsed_range_ms": [min(elapsed), max(elapsed)], "all": observations})
print(f"{name:30s} number={first['number']:<4} bound={first['bound']!s:5s} "
f"identical={identical} elapsed={first['elapsed_ms']} ms")
probe.save("02", "bind", {"repeats": probe.REPEATS, "arms": arms})
if __name__ == "__main__":
main()
Five arms at each of three polling intervals, all fifteen at once. 03_timewait.py
"""Probe 03: how long a port stays unusable after the process that held it exits.
Five arms run at each of three polling intervals at the same time - fifteen arms in all, each on
its own port - so no arm can queue behind another: a listener accepts one connection, the server
side closes it first, the listener closes, and then a plain bind is attempted every interval until
it succeeds. The probe records the wait, the number of attempts, and the kernel's own state for
the port at the moment the wait began. The three intervals are the point: the timer is one fixed
number, and what a reader sees is that number plus up to one polling step.
"""
from __future__ import annotations
import pathlib
import socket
import statistics
import sys
import threading
import time
import probe
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "module"))
from portguard.table import states_for_port # noqa: E402
TIMEOUT_S = 100.0
INTERVALS_S = (0.1, 0.5, 1.0)
TABLE_INTERVAL_S = 0.5
def close_first(port: int) -> None:
"""Leave one TIME_WAIT entry on ``port``: the server closes the connection first."""
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
time.sleep(0.01)
def one_arm(result: dict, index: int, interval_s: float) -> None:
port = probe.free_port()
close_first(port)
states_at_zero = states_for_port(port)
started = time.monotonic()
attempts = 0
while True:
attempts += 1
outcome = probe.attempt_bind(port)
if outcome["bound"]:
break
waited = time.monotonic() - started
if waited >= TIMEOUT_S:
break
time.sleep(interval_s)
waited = time.monotonic() - started
result[(interval_s, index)] = {
"interval_s": interval_s, "port": port, "wait_ms": round(waited * 1000, 1),
"attempts": attempts, "bound": outcome["bound"], "states_at_zero": states_at_zero}
def summarize(results: dict, interval_s: float) -> dict:
"""One interval's five arms, and the three figures a polled wait can honestly report."""
arms = [results[(interval_s, index)] for index in range(probe.REPEATS)]
waits = [arm["wait_ms"] for arm in arms]
attempts = [arm["attempts"] for arm in arms]
return {
"interval_s": interval_s,
"arms": arms,
"wait_ms": {"min": min(waits), "median": statistics.median(waits), "max": max(waits)},
"attempts": {"min": min(attempts), "median": statistics.median(attempts),
"max": max(attempts)},
"identical": len(set(waits)) == 1,
"time_wait_at_zero": [arm["states_at_zero"].get("TIME_WAIT", 0) for arm in arms],
}
def main() -> None:
results: dict[tuple[float, int], dict] = {}
threads = [threading.Thread(target=one_arm, args=(results, index, interval_s))
for interval_s in INTERVALS_S for index in range(probe.REPEATS)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
groups = [summarize(results, interval_s) for interval_s in INTERVALS_S]
table_group = next(group for group in groups if group["interval_s"] == TABLE_INTERVAL_S)
payload = {
"timeout_s": TIMEOUT_S,
"interval_s": TABLE_INTERVAL_S,
"intervals_s": list(INTERVALS_S),
"repeats": probe.REPEATS,
"arms": table_group["arms"],
"wait_ms": table_group["wait_ms"],
"identical": table_group["identical"],
"time_wait_at_zero": table_group["time_wait_at_zero"],
"groups": groups,
}
for group in groups:
print(group["interval_s"], "s:", group["wait_ms"], group["attempts"],
"identical:", group["identical"])
probe.save("03", "timewait", payload)
if __name__ == "__main__":
main()
Seven arms around one TIME_WAIT entry, including who set the flag. 04_reuse.py
"""Probe 04: the two reuse flags against the two places a port can be stuck.
The server side of a restart, and an outbound client that must keep its source port: each arm
records the number its bind returned and, where a connection follows, whether the connect worked
from the port that had just been in TIME_WAIT.
"""
from __future__ import annotations
import socket
import time
import probe
def rebind_reuseaddr() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
return probe.attempt_bind(port, reuse_addr=True)
def rebind_plain() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
return probe.attempt_bind(port)
def client_port_wait(port: int) -> int:
"""The local port a client used for one connection to ``port``, left in TIME_WAIT."""
listener = probe.listen(port)
client = socket.socket()
client.bind(("127.0.0.1", 0))
local = client.getsockname()[1]
client.connect(("127.0.0.1", port))
server, _ = listener.accept()
client.close() # the client closes first: its own port waits
time.sleep(0.05)
probe.close_quietly(server)
probe.close_quietly(listener)
return local
def client_rebind_plain() -> dict:
port = probe.free_port()
local = client_port_wait(port)
return probe.attempt_bind(local)
def client_rebind_reuseaddr() -> dict:
port = probe.free_port()
local = client_port_wait(port)
outcome = probe.attempt_bind(local, reuse_addr=True)
if not outcome["bound"]:
return outcome
listener = probe.listen(port)
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", local))
try:
sock.connect(("127.0.0.1", port))
accept = listener.accept()
probe.close_quietly(accept[0])
outcome["connect"] = "ok"
except OSError as exc:
outcome["connect"] = f"{type(exc).__name__} {exc.errno}"
finally:
probe.close_quietly(sock)
probe.close_quietly(listener)
return outcome
def client_fresh_port() -> dict:
port = probe.free_port()
local = client_port_wait(port)
listener = probe.listen(port)
sock = socket.socket()
started = time.perf_counter()
try:
sock.connect(("127.0.0.1", port))
accept = listener.accept()
probe.close_quietly(accept[0])
outcome = {"bound": True, "number": 0, "error": None,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3),
"connect": "ok", "local_port": sock.getsockname()[1], "waited_port": local}
except OSError as exc:
outcome = {"bound": False, "number": int(exc.errno or 0), "error": type(exc).__name__,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3),
"connect": "failed", "local_port": None, "waited_port": local}
finally:
probe.close_quietly(sock)
probe.close_quietly(listener)
return outcome
def client_port_wait_with_flag(port: int) -> int:
"""The same, with SO_REUSEADDR set on the socket that will own the TIME_WAIT entry."""
listener = probe.listen(port)
client = socket.socket()
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client.bind(("127.0.0.1", 0))
local = client.getsockname()[1]
client.connect(("127.0.0.1", port))
server, _ = listener.accept()
client.close()
time.sleep(0.05)
probe.close_quietly(server)
probe.close_quietly(listener)
time.sleep(0.05)
return local
def reconnect_from(local: int, port: int, outcome: dict) -> dict:
"""Connect again from the port that waited, and say what the kernel answered."""
if not outcome["bound"]:
return outcome
listener = probe.listen(port)
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", local))
try:
sock.connect(("127.0.0.1", port))
accepted, _ = listener.accept()
probe.close_quietly(accepted)
outcome["connect"] = "ok"
except OSError as exc:
outcome["connect"] = f"{type(exc).__name__} {exc.errno}"
finally:
probe.close_quietly(sock)
probe.close_quietly(listener)
return outcome
def client_flag_then_reuseaddr() -> dict:
port = probe.free_port()
local = client_port_wait_with_flag(port)
return reconnect_from(local, port, probe.attempt_bind(local, reuse_addr=True))
def listener_strict_then_reuseaddr() -> dict:
port = probe.free_port()
listener = probe.listen(port, reuse_addr=False)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
time.sleep(0.05)
return probe.attempt_bind(port, reuse_addr=True)
ARMS = {
"rebind_reuseaddr": rebind_reuseaddr,
"rebind_plain": rebind_plain,
"client_rebind_plain": client_rebind_plain,
"client_rebind_reuseaddr": client_rebind_reuseaddr,
"client_flag_then_reuseaddr": client_flag_then_reuseaddr,
"listener_strict_then_reuseaddr": listener_strict_then_reuseaddr,
"client_fresh_port": client_fresh_port,
}
def main() -> None:
arms = []
for name, call in ARMS.items():
observations = probe.repeat(call)
first = observations[0]
identical = all(observation["number"] == first["number"] for observation in observations)
arms.append({"name": name, "repeats": len(observations), "identical": identical,
"number": first["number"], "bound": first["bound"],
"error": first["error"], "elapsed_ms": first["elapsed_ms"],
"connect": first.get("connect"), "all": observations})
print(f"{name:24s} number={first['number']:<4} bound={first['bound']!s:5s} "
f"connect={first.get('connect')} identical={identical}")
probe.save("04", "reuse", {"repeats": probe.REPEATS, "arms": arms})
if __name__ == "__main__":
main()
Two listeners on one port, and whichever socket the kernel picks. 05_reuseport.py
"""Probe 05: what the kernel does with two listeners that share a port under SO_REUSEPORT.
Two sockets join the same port, and then two hundred connections are made one at a time. Each
connection is accepted by whichever socket the kernel chose, so the counts show the split rather
than the intent.
"""
from __future__ import annotations
import select
import socket
import probe
CONNECTIONS = 200
def one_round() -> dict:
port = probe.free_port()
first = probe.listen(port, reuse_port=True)
second = probe.listen(port, reuse_port=True)
counts = [0, 0]
try:
for _ in range(CONNECTIONS):
client = socket.create_connection(("127.0.0.1", port))
ready, _, _ = select.select([first, second], [], [], 2.0)
if not ready:
client.close()
continue
accepted, _ = ready[0].accept()
counts[0 if ready[0] is first else 1] += 1
accepted.close()
client.close()
finally:
probe.close_quietly(first)
probe.close_quietly(second)
return {"counts": counts, "total": sum(counts), "port": port}
def main() -> None:
rounds = probe.repeat(one_round)
a = [round_["counts"][0] for round_ in rounds]
b = [round_["counts"][1] for round_ in rounds]
payload = {
"connections": CONNECTIONS,
"repeats": probe.REPEATS,
"rounds": rounds,
"listener_a": probe.summary(a),
"listener_b": probe.summary(b),
"identical": len({tuple(round_["counts"]) for round_ in rounds}) == 1,
"share_min": min(a) / CONNECTIONS,
"share_max": max(a) / CONNECTIONS,
}
for round_ in rounds:
print(round_["counts"])
print("a:", payload["listener_a"], "b:", payload["listener_b"],
"identical:", payload["identical"])
probe.save("05", "reuseport", payload)
if __name__ == "__main__":
main()
One connection ended three ways, and the entry counted on both ports. 06_tw_owner.py
"""Probe 06: which side of a closed connection owns the TIME_WAIT entry.
Three ways to end one connection - the client closes first, the server closes first, or the client
resets - and then the kernel's table is read for both ports. The side that sends the first FIN is
the side that keeps the entry, which is why an outbound client with a fixed source port can lose it
while the server it talked to never notices.
"""
from __future__ import annotations
import pathlib
import socket
import sys
import time
import probe
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "module"))
from portguard.table import states_for_port # noqa: E402
def settle() -> None:
"""After both ends are closed, give the kernel a moment to move the entry to TIME_WAIT."""
time.sleep(0.1)
def client_close_first() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.socket()
client.bind(("127.0.0.1", 0))
local = client.getsockname()[1]
client.connect(("127.0.0.1", port))
server, _ = listener.accept()
client.close()
probe.close_quietly(server) # the second FIN moves the first closer to TIME_WAIT
settle()
states = {"client": states_for_port(local), "server": states_for_port(port)}
probe.close_quietly(listener)
return {"client_time_wait": states["client"].get("TIME_WAIT", 0),
"server_time_wait": states["server"].get("TIME_WAIT", 0),
"client_states": states["client"], "server_states": states["server"]}
def server_close_first() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.socket()
client.bind(("127.0.0.1", 0))
local = client.getsockname()[1]
client.connect(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
probe.close_quietly(client) # the second FIN moves the first closer to TIME_WAIT
settle()
states = {"client": states_for_port(local), "server": states_for_port(port)}
probe.close_quietly(listener)
return {"client_time_wait": states["client"].get("TIME_WAIT", 0),
"server_time_wait": states["server"].get("TIME_WAIT", 0),
"client_states": states["client"], "server_states": states["server"]}
def client_reset() -> dict:
port = probe.free_port()
listener = probe.listen(port)
client = socket.socket()
client.bind(("127.0.0.1", 0))
local = client.getsockname()[1]
client.connect(("127.0.0.1", port))
server, _ = listener.accept()
client.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\x01\x00\x00\x00\x00\x00\x00\x00")
client.close()
probe.close_quietly(server) # the second FIN moves the first closer to TIME_WAIT
settle()
states = {"client": states_for_port(local), "server": states_for_port(port)}
probe.close_quietly(listener)
return {"client_time_wait": states["client"].get("TIME_WAIT", 0),
"server_time_wait": states["server"].get("TIME_WAIT", 0),
"client_states": states["client"], "server_states": states["server"]}
ARMS = {
"client_close_first": client_close_first,
"server_close_first": server_close_first,
"client_reset": client_reset,
}
def main() -> None:
arms = []
for name, call in ARMS.items():
observations = probe.repeat(call)
first = observations[0]
identical = all(observation["client_time_wait"] == first["client_time_wait"]
and observation["server_time_wait"] == first["server_time_wait"]
for observation in observations)
arms.append({"name": name, "repeats": len(observations), "identical": identical,
"client_time_wait": first["client_time_wait"],
"server_time_wait": first["server_time_wait"],
"client_states": first["client_states"],
"server_states": first["server_states"], "all": observations})
print(f"{name:20s} client_tw={first['client_time_wait']} "
f"server_tw={first['server_time_wait']} identical={identical}")
probe.save("06", "tw_owner", {"repeats": probe.REPEATS, "arms": arms})
if __name__ == "__main__":
main()
The classifier and the owner’s verdict, on live failures and one non-bind. 07_policy.py
"""Probe 07: the classifier against live failures from this kernel, and one that is not a bind.
Five errnos, four of them produced on purpose by a real bind, the fifth produced by writing into a
pipe whose reader has gone. Two of the bind arms share errno 98 and differ only in the owner the
kernel's table reports - a live listener and a lone TIME_WAIT entry - which is the pair the
classifier has to answer differently. The point is that the fourth is refused as a port problem.
"""
from __future__ import annotations
import errno
import os
import pathlib
import socket
import sys
import time
import probe
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "module"))
from portguard.errors import Kind, advise # noqa: E402
from portguard.report import describe_bind_failure # noqa: E402
from portguard.table import states_for_port # noqa: E402
def raise_and_classify(action, address: tuple[str, int], port: int | None = None) -> dict:
try:
action()
except OSError as exc:
states = states_for_port(port) if port is not None else None
fault = advise(exc, states)
return {"number": int(exc.errno or 0), "kind": fault.kind.value, "name": fault.name,
"retry_budget": fault.retry_budget, "wait_s": fault.wait_s,
"remedy": fault.remedy, "states": states,
"line": describe_bind_failure(exc, address, states)}
return {"number": 0, "kind": "none", "name": "none", "retry_budget": 0, "wait_s": 0.0,
"remedy": "", "states": None, "line": ""}
def live_listener_bind() -> dict:
port = probe.free_port()
listener = probe.listen(port)
try:
return raise_and_classify(lambda: probe.attempt_bind_strict(port), ("127.0.0.1", port),
port)
finally:
probe.close_quietly(listener)
def time_wait_bind() -> dict:
"""One TIME_WAIT entry and nothing else: the server closed the connection first."""
port = probe.free_port()
listener = probe.listen(port)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
probe.close_quietly(client)
probe.close_quietly(listener)
time.sleep(0.05)
return raise_and_classify(lambda: probe.attempt_bind_strict(port), ("127.0.0.1", port), port)
def foreign_address_bind() -> dict:
return raise_and_classify(lambda: probe.attempt_bind_strict(0, host="10.255.255.1"),
("10.255.255.1", 0))
def privileged_bind() -> dict:
return raise_and_classify(lambda: probe.attempt_bind_strict(80), ("127.0.0.1", 80))
def pipe_write() -> dict:
read_fd, write_fd = os.pipe()
os.close(read_fd)
try:
return raise_and_classify(lambda: os.write(write_fd, b"x"), ("pipe", 0))
finally:
os.close(write_fd)
ARMS = {
"live_listener_bind": live_listener_bind,
"time_wait_bind": time_wait_bind,
"foreign_address_bind": foreign_address_bind,
"privileged_bind": privileged_bind,
"pipe_write": pipe_write,
}
def main() -> None:
arms = []
for name, call in ARMS.items():
observations = probe.repeat(call)
first = observations[0]
identical = all(observation["kind"] == first["kind"]
and observation["number"] == first["number"]
and observation["wait_s"] == first["wait_s"]
for observation in observations)
arms.append({"name": name, "repeats": len(observations), "identical": identical, **first})
print(f"{name:22s} number={first['number']:<4} kind={first['kind']:15s} "
f"wait={first['wait_s']} retries={first['retry_budget']} identical={identical}")
kinds: dict[str, int] = {}
for arm in arms:
kinds[arm["kind"]] = kinds.get(arm["kind"], 0) + 1
bind_arms = [arm for arm in arms if arm["name"] != "pipe_write"]
payload = {
"repeats": probe.REPEATS,
"arms": arms,
"kinds": kinds,
"table_rows": len({errno.EADDRINUSE, errno.EADDRNOTAVAIL, errno.EACCES}),
"bind_arms": len(bind_arms),
"retry_budget_total": sum(arm["retry_budget"] for arm in bind_arms),
"wait_arms": sum(1 for arm in bind_arms if arm["wait_s"] > 0),
"invariant_violations": sum(1 for arm in arms
if arm["wait_s"] > 0 and arm["retry_budget"] > 0),
"unrelated": kinds.get(Kind.UNRELATED.value, 0),
"remedies": len({arm["remedy"] for arm in arms if arm["remedy"]}),
}
print(payload["kinds"], "wait arms", payload["wait_arms"], "retry", payload["retry_budget_total"])
probe.save("07", "policy", payload)
if __name__ == "__main__":
main()
pytest’s own summary, and the line counts the article quotes. 08_tests.py
"""Probe 08: the package's own test run, and the counts the article quotes.
The passed count comes from pytest's own summary line, and the line and file counts are read from
the tree, so a sentence about how many tests there are cannot outlive the tests.
"""
from __future__ import annotations
import json
import pathlib
import re
import subprocess
import sys
import probe
HERE = pathlib.Path(__file__).resolve().parent
PACKAGE = HERE.parent / "module" / "portguard"
def count(paths: list[pathlib.Path]) -> tuple[int, int]:
files = 0
lines = 0
for path in paths:
files += 1
lines += len(path.read_text(encoding="utf-8").splitlines())
return files, lines
def main() -> None:
result = subprocess.run([sys.executable, "-m", "pytest", "portguard/tests", "-q",
"-p", "no:warnings"], cwd=str(PACKAGE.parent),
capture_output=True, text=True)
summary = result.stdout.strip().splitlines()[-1] if result.stdout.strip() else ""
match = re.search(r"(\d+) passed", summary)
passed = int(match.group(1)) if match else 0
test_files, test_lines = count(sorted((PACKAGE / "tests").glob("*.py")))
package_files, package_lines = count(sorted(PACKAGE.glob("*.py")))
probe_files = len(list(HERE.glob("[0-9][0-9]_*.py")))
payload = {
"pytest_passed": passed,
"pytest_summary": summary,
"pytest_returncode": result.returncode,
"test_files": test_files,
"test_lines": test_lines,
"package_files": package_files,
"package_lines": package_lines,
"probe_files": probe_files,
}
print(json.dumps(payload, indent=1))
probe.save("08", "tests", payload)
if result.returncode != 0:
raise SystemExit(result.stdout[-2000:] + result.stderr[-2000:])
if __name__ == "__main__":
main()
What a service imports from the package. portguard/__init__.py
"""portguard: bind a port on purpose, and read the failure when it will not.
A service restart meets one of three errnos, and each one asks for a different change. The package
names them (``errors``), applies the two reuse flags by role (``reuse``), reads which side of a
closed connection still holds a port (``table``), waits for a port with a written-down interval
(``wait``), and prints one line an on-call reader can act on (``report``).
"""
from __future__ import annotations
from .errors import (TABLE, TIME_WAIT_S, Fault, Kind, advise, classify, is_conflict, unwrap,
wait_budget)
from .reuse import CLIENT, FLEET, SERVICE, STRICT, Policy, apply, bind_client_source, bind_listener
from .table import states_for_port, table_text, time_wait_count
from .wait import WaitResult, can_bind, wait_for_bind
__all__ = [
"TABLE", "TIME_WAIT_S", "Fault", "Kind", "advise", "classify", "is_conflict", "unwrap",
"wait_budget", "CLIENT", "FLEET", "SERVICE", "STRICT", "Policy", "apply", "bind_client_source",
"bind_listener", "states_for_port", "table_text", "time_wait_count", "WaitResult", "can_bind",
"wait_for_bind",
]
Errno to Fault, and the wait the port’s owner decides. portguard/errors.py
"""Errno to Fault: what a bind failure means, what to do about it, and how long to wait.
A bind failure is one of three things on this platform - another socket owns the port, the address
cannot be used from here, or the port is below the unprivileged start - and the number alone is not
enough to tell them apart from a mistyped address. ``TABLE`` names the three, ``classify`` follows a
wrapped exception to the first ``OSError`` that carries one of them, and anything else comes back as
unrelated rather than being quietly retried.
The wait is a second question. ``advise`` answers it with the kernel's table in hand: a socket
that is still listening, connected or closing is held by a process, not by the timer this page
waits out, and only a port whose owners are all TIME_WAIT is worth waiting for. Without the table
it returns the number's generic advice and promises no wait.
"""
from __future__ import annotations
import errno
from dataclasses import dataclass, replace
from enum import Enum
TIME_WAIT_S = 60.0
# Every state in which a socket still holds the port. A live owner keeps it until its process
# closes it; an orphaned socket on its way out is reaped by a kernel timer this wait does not
# model (tcp_fin_timeout for FIN_WAIT2, the retransmit timeout for LAST_ACK).
LIVE_STATES = ("LISTEN", "SYN_SENT", "SYN_RECV", "ESTABLISHED")
CLOSING_STATES = ("FIN_WAIT1", "FIN_WAIT2", "CLOSE", "CLOSE_WAIT", "CLOSING", "LAST_ACK")
class Kind(Enum):
"""The three ways a bind fails, and the group everything else falls into."""
IN_USE = "in_use"
NOT_AVAILABLE = "not_available"
PERMISSION = "permission"
UNRELATED = "unrelated"
@dataclass(frozen=True)
class Fault:
"""One errno, what it means for a bind, and the one action it is worth.
``wait_s`` and ``retry_budget`` are never both set: a fault asks for a wait or for a retry,
and a row that asked for both would tell a caller to sleep through a conflict it could not
outlast.
"""
number: int
name: str
kind: Kind
remedy: str
retry_budget: int
wait_s: float = 0.0
TABLE = {
errno.EADDRINUSE: Fault(
errno.EADDRINUSE, "EADDRINUSE", Kind.IN_USE,
"find the socket that owns the port before deciding anything else", 0),
errno.EADDRNOTAVAIL: Fault(
errno.EADDRNOTAVAIL, "EADDRNOTAVAIL", Kind.NOT_AVAILABLE,
"check that the address belongs to this host; for an outbound connect, retry once from "
"another source port", 1, 0.0),
errno.EACCES: Fault(
errno.EACCES, "EACCES", Kind.PERMISSION,
"bind a port at or above the unprivileged start, or grant the process "
"CAP_NET_BIND_SERVICE", 0, 0.0),
}
def unwrap(exc: BaseException) -> BaseException:
"""The first exception in the cause chain that is an ``OSError``, or the one given."""
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
seen.add(id(current))
if isinstance(current, OSError):
return current
current = current.__cause__ or current.__context__
return exc
def classify(exc: BaseException) -> Fault:
"""Map an exception to a row of ``TABLE``, or to an unrelated fault that keeps its number."""
error = unwrap(exc)
number = int(getattr(error, "errno", 0) or 0)
if number in TABLE:
return TABLE[number]
return Fault(number, errno.errorcode.get(number, "unknown"), Kind.UNRELATED,
"not a bind conflict: read the full traceback before acting", 0, 0.0)
def advise(exc: BaseException, states: dict[str, int] | None = None) -> Fault:
"""The fault, with its wait corrected by who is still holding the port.
``states`` is what the kernel's table reports for the port (``states_for_port``): a listener,
a connection or a socket that is still closing means the answer is to stop that owner,
TIME_WAIT alone means the answer is one timer, and no entry at all means the bind is worth
one more attempt.
"""
fault = classify(exc)
if fault.kind is not Kind.IN_USE or states is None:
return fault
if any(states.get(state) for state in LIVE_STATES):
return replace(fault, retry_budget=0, wait_s=0.0,
remedy="a live socket owns the port: stop that process, or bind another "
"port; no timer clears it")
if any(states.get(state) for state in CLOSING_STATES):
return replace(fault, retry_budget=0, wait_s=0.0,
remedy="a closing or half-closed socket owns the port: stop that process, "
"or bind another port; only TIME_WAIT ends on a clock this wait keeps")
if states.get("TIME_WAIT"):
return replace(fault, retry_budget=0, wait_s=TIME_WAIT_S,
remedy="only TIME_WAIT entries remain: wait one timer, or set SO_REUSEADDR "
"on the socket that owns the entry before its first bind")
return replace(fault, retry_budget=1, wait_s=0.0,
remedy="the table shows no owner now: retry the bind once")
def is_conflict(exc: BaseException) -> bool:
"""True when the port, and not the address or the privilege level, is the problem."""
return classify(exc).kind is Kind.IN_USE
def wait_budget(exc: BaseException) -> float:
"""How long the number alone is worth waiting - zero until the owner is known."""
return classify(exc).wait_s
The two flags, chosen by the role the socket plays. portguard/reuse.py
"""Binding a port with the two reuse flags, and what each flag is for.
``SO_REUSEADDR`` lets a new socket bind a port whose previous owner left TIME_WAIT entries; it does
not let two sockets listen on one address. ``SO_REUSEPORT`` does allow that, and the kernel spreads
incoming connections across the sockets that joined. ``Policy`` names the four shapes a service
needs, so the flags are chosen by role instead of copied from a tutorial.
"""
from __future__ import annotations
import socket
from dataclasses import dataclass
@dataclass(frozen=True)
class Policy:
"""The two flags, plus a name for the role that wants them."""
name: str
reuse_addr: bool
reuse_port: bool
SERVICE = Policy("service", reuse_addr=True, reuse_port=False)
FLEET = Policy("fleet", reuse_addr=True, reuse_port=True)
CLIENT = Policy("client", reuse_addr=True, reuse_port=False)
STRICT = Policy("strict", reuse_addr=False, reuse_port=False)
def apply(sock: socket.socket, policy: Policy) -> socket.socket:
"""Set the options a policy asks for, before any bind."""
if policy.reuse_addr:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if policy.reuse_port:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
return sock
def bind_listener(address: tuple[str, int], policy: Policy = SERVICE,
backlog: int = 128) -> socket.socket:
"""A listening socket, or the exception the bind raised, with nothing left open behind it."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
apply(sock, policy)
try:
sock.bind(address)
sock.listen(backlog)
except OSError:
sock.close()
raise
return sock
def bind_client_source(address: tuple[str, int], remote: tuple[str, int],
timeout_s: float = 2.0) -> socket.socket:
"""An outbound socket from a chosen source port, for a client that must keep one."""
sock = apply(socket.socket(socket.AF_INET, socket.SOCK_STREAM), CLIENT)
sock.settimeout(timeout_s)
try:
sock.bind(address)
sock.connect(remote)
except OSError:
sock.close()
raise
return sock
Both kernel socket tables, read per local port. portguard/table.py
"""Reading the kernel's own socket tables: who holds a port, and in which state.
``/proc/net/tcp`` is one line per IPv4 socket, ``/proc/net/tcp6`` the same for IPv6, with the local
port in hex and the state in a two-byte code. Both are read here without a dependency, because a
listener on ``::`` owns the IPv4 port too and an owner that only one file lists is the owner a
reader misses.
"""
from __future__ import annotations
import pathlib
TABLE_PATHS = (pathlib.Path("/proc/net/tcp"), pathlib.Path("/proc/net/tcp6"))
TIME_WAIT = "06"
STATE_NAMES = {
"01": "ESTABLISHED",
"02": "SYN_SENT",
"03": "SYN_RECV",
"04": "FIN_WAIT1",
"05": "FIN_WAIT2",
"06": "TIME_WAIT",
"07": "CLOSE",
"08": "CLOSE_WAIT",
"09": "LAST_ACK",
"0A": "LISTEN",
"0B": "CLOSING",
}
def local_port(line: str) -> int | None:
"""The local port of one table line, or None when the line is not a socket."""
fields = line.split()
if len(fields) < 4 or not fields[0].rstrip(":").isdigit():
return None
_, _, port = fields[1].partition(":")
if not port:
return None
try:
return int(port, 16)
except ValueError:
return None
def state_code(line: str) -> str | None:
"""The two-byte state of one table line, or None when it is not one this table names."""
fields = line.split()
if len(fields) < 4 or fields[3] not in STATE_NAMES:
return None
return fields[3]
def parse(text: str) -> list[dict]:
"""Every socket in a table file, as local port and state name."""
entries: list[dict] = []
for line in (text or "").splitlines()[1:]:
port = local_port(line)
code = state_code(line)
if port is None or code is None:
continue
entries.append({"local_port": port, "state": STATE_NAMES[code]})
return entries
def table_text(paths: tuple[pathlib.Path, ...] = TABLE_PATHS) -> str:
"""Both kernel tables as one text; a host that has no IPv6 simply has no second file."""
texts: list[str] = []
for path in paths:
try:
texts.append(path.read_text(encoding="utf-8"))
except OSError:
continue
return "\n".join(texts)
def states_for_port(port: int, text: str | None = None) -> dict[str, int]:
"""How many sockets on one local port are in each state, as the kernel reports them."""
table = table_text() if text is None else text
counts: dict[str, int] = {}
for entry in parse(table):
if entry["local_port"] == port:
counts[entry["state"]] = counts.get(entry["state"], 0) + 1
return counts
def time_wait_count(port: int, text: str | None = None) -> int:
"""How many TIME_WAIT entries one local port carries right now."""
return states_for_port(port, text).get("TIME_WAIT", 0)
A wait with a stated interval, and the result it returns. portguard/wait.py
"""Waiting for a port to become bindable, and reporting how long it took.
A restart that finds its port in TIME_WAIT has two honest choices: set SO_REUSEADDR and start now,
or wait. This waits, with the interval written down, so a runbook step can report the seconds it
actually took instead of sleeping for a guessed number.
"""
from __future__ import annotations
import socket
import time
from dataclasses import dataclass
from .reuse import STRICT, Policy, apply
@dataclass(frozen=True)
class WaitResult:
"""One wait: how long it took, how many attempts, and whether the port ever came free."""
seconds: float
attempts: int
bound: bool
def can_bind(address: tuple[str, int], policy: Policy = STRICT) -> bool:
"""Whether one plain bind of this address would succeed right now."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
apply(sock, policy)
try:
sock.bind(address)
return True
except OSError:
return False
finally:
sock.close()
def wait_for_bind(address: tuple[str, int], timeout_s: float = 90.0,
interval_s: float = 0.5, policy: Policy = STRICT) -> WaitResult:
"""Poll a plain bind until it succeeds or the timeout passes.
The default policy sets no flag: a waiter that set SO_REUSEADDR on its own socket would skip
the very entry it is waiting for and return at once, which is the mistake this module exists
to prevent. Pass ``SERVICE`` only to ask whether a flagged bind would work now.
"""
started = time.monotonic()
attempts = 0
while True:
attempts += 1
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
apply(sock, policy)
try:
sock.bind(address)
return WaitResult(round(time.monotonic() - started, 3), attempts, True)
except OSError:
pass
finally:
sock.close()
if time.monotonic() - started >= timeout_s:
return WaitResult(round(time.monotonic() - started, 3), attempts, False)
time.sleep(interval_s)
One log line for a failed bind. portguard/report.py
"""One log line for a failed bind, with the fields an on-call reader needs.
A traceback says where the code was. It does not say which port, which of the three causes, or
whether waiting would help - so the line this module prints carries those instead, and the number
keeps its own name.
"""
from __future__ import annotations
from .errors import advise
def describe_bind_failure(exc: BaseException, address: tuple[str, int],
states: dict[str, int] | None = None) -> str:
"""One line: address, number, name, cause, wait, retries and the remedy.
Pass ``states`` from the kernel's table and the wait becomes the owner's answer; without it
the line keeps the number's generic advice and claims no wait.
"""
fault = advise(exc, states)
host, port = address
return (f"bind {host}:{port} failed: {fault.name} ({fault.number}) {fault.kind.value}; "
f"wait {fault.wait_s:g} s, retries {fault.retry_budget}; {fault.remedy}")
A free port and a port held by a live listener. conftest.py
"""Fixtures: a port the kernel called free, and a listener that holds one."""
from __future__ import annotations
import socket
import pytest
def _free_port() -> int:
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
return port
@pytest.fixture()
def free_port() -> int:
"""A port that was free a moment ago, with nothing listening on it."""
return _free_port()
@pytest.fixture()
def held_port():
"""A port held by a live listener, returned with that listener."""
port = _free_port()
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", port))
listener.listen(4)
try:
yield port, listener
finally:
listener.close()
Classification, the owner’s wait, and the one-action rule. test_errors.py
"""Classification: the three bind errnos, the wait their owner decides, and everything else."""
from __future__ import annotations
import errno
import socket
import pytest
from portguard.errors import (CLOSING_STATES, LIVE_STATES, TABLE, TIME_WAIT_S, Fault, Kind,
advise, classify, is_conflict, unwrap, wait_budget)
def test_addr_in_use_is_a_conflict():
fault = classify(OSError(errno.EADDRINUSE, "Address already in use"))
assert fault.kind is Kind.IN_USE
assert fault.name == "EADDRINUSE"
def test_the_number_alone_promises_no_wait():
"""Without the table the classifier cannot know whether waiting would help."""
fault = TABLE[errno.EADDRINUSE]
assert fault.retry_budget == 0
assert fault.wait_s == 0
def test_a_live_owner_asks_for_a_stop_not_a_wait():
fault = advise(OSError(errno.EADDRINUSE, "x"), {"LISTEN": 1})
assert fault.wait_s == 0
assert fault.retry_budget == 0
assert "live socket" in fault.remedy
@pytest.mark.parametrize("state", ["FIN_WAIT1", "FIN_WAIT2", "CLOSING", "LAST_ACK",
"SYN_SENT", "SYN_RECV"])
def test_a_socket_still_closing_owns_the_port(state):
"""A half-closed or handshaking socket holds the port; the wait times only TIME_WAIT."""
fault = advise(OSError(errno.EADDRINUSE, "x"), {state: 1})
assert fault.wait_s == 0
assert fault.retry_budget == 0
assert "live socket" in fault.remedy or "only TIME_WAIT" in fault.remedy
def test_a_closing_entry_is_not_an_empty_table():
"""The exact pair the classifier used to send back as \"no owner, retry once\"."""
fault = advise(OSError(errno.EADDRINUSE, "x"), {"FIN_WAIT2": 1, "LAST_ACK": 2})
assert fault.wait_s == 0
assert fault.retry_budget == 0
def test_every_kernel_state_but_time_wait_is_an_owner():
"""The two tuples name exactly the states the table can report, minus TIME_WAIT."""
from portguard.table import STATE_NAMES
assert set(LIVE_STATES) | set(CLOSING_STATES) == set(STATE_NAMES.values()) - {"TIME_WAIT"}
def test_only_time_wait_asks_for_one_timer():
fault = advise(OSError(errno.EADDRINUSE, "x"), {"TIME_WAIT": 2})
assert fault.wait_s == TIME_WAIT_S
assert fault.retry_budget == 0
assert "SO_REUSEADDR" in fault.remedy
def test_an_empty_table_asks_for_one_more_attempt():
fault = advise(OSError(errno.EADDRINUSE, "x"), {})
assert fault.wait_s == 0
assert fault.retry_budget == 1
def test_no_row_asks_for_a_wait_and_a_retry():
states = ({}, {"LISTEN": 1}, {"TIME_WAIT": 1}, {"ESTABLISHED": 3}, {"CLOSE_WAIT": 1})
for row in list(TABLE.values()) + [advise(OSError(errno.EADDRINUSE, "x"), s) for s in states]:
assert not (row.wait_s and row.retry_budget), row
def test_addr_not_available_is_not_a_conflict():
fault = classify(OSError(errno.EADDRNOTAVAIL, "Cannot assign requested address"))
assert fault.kind is Kind.NOT_AVAILABLE
assert not is_conflict(OSError(errno.EADDRNOTAVAIL, "x"))
def test_permission_is_its_own_kind():
fault = classify(PermissionError(errno.EACCES, "Permission denied"))
assert fault.kind is Kind.PERMISSION
assert "CAP_NET_BIND_SERVICE" in fault.remedy
def test_an_unlisted_errno_keeps_its_number():
fault = classify(OSError(errno.ENOENT, "No such file or directory"))
assert fault.kind is Kind.UNRELATED
assert fault.number == errno.ENOENT
assert fault.name == "ENOENT"
def test_a_missing_errno_is_unrelated_not_a_crash():
fault = classify(ValueError("no errno here"))
assert fault.kind is Kind.UNRELATED
assert fault.number == 0
def test_unwrap_follows_the_cause_chain():
inner = OSError(errno.EADDRINUSE, "Address already in use")
outer = RuntimeError("could not start the worker")
outer.__cause__ = inner
assert unwrap(outer) is inner
assert classify(outer).kind is Kind.IN_USE
def test_unwrap_survives_a_cycle():
first = RuntimeError("first")
second = RuntimeError("second")
first.__context__ = second
second.__context__ = first
assert unwrap(first) is first
def test_wait_budget_reads_the_table():
assert wait_budget(OSError(errno.EADDRINUSE, "x")) == 0
assert wait_budget(OSError(errno.EACCES, "x")) == 0
def test_fault_is_frozen():
fault = TABLE[errno.EADDRINUSE]
with pytest.raises(Exception):
fault.number = 1 # type: ignore[misc]
def test_a_real_bind_failure_classifies(held_port):
port, _ = held_port
sock = socket.socket()
try:
with pytest.raises(OSError) as caught:
sock.bind(("127.0.0.1", port))
finally:
sock.close()
fault = classify(caught.value)
assert fault.kind is Kind.IN_USE
assert fault.number == errno.EADDRINUSE
def test_every_table_row_names_itself():
for number, fault in TABLE.items():
assert isinstance(fault, Fault)
assert fault.number == number
assert fault.name == errno.errorcode[number]
assert fault.remedy
The flags, a second listener, and a failed bind that leaves no socket. test_reuse.py
"""The two reuse flags: a restart with SO_REUSEADDR, a fleet with SO_REUSEPORT."""
from __future__ import annotations
import errno
import os
import socket
import pytest
from portguard.reuse import (CLIENT, FLEET, SERVICE, STRICT, Policy, apply, bind_client_source,
bind_listener)
def fds() -> int:
return len(os.listdir("/proc/self/fd"))
def test_bind_listener_returns_a_listening_socket(free_port):
listener = bind_listener(("127.0.0.1", free_port), STRICT)
try:
assert listener.getsockname() == ("127.0.0.1", free_port)
assert listener.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN) == 1
finally:
listener.close()
def test_service_policy_sets_reuseaddr(free_port):
listener = bind_listener(("127.0.0.1", free_port), SERVICE)
try:
assert listener.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1
finally:
listener.close()
def test_strict_policy_leaves_reuseaddr_off(free_port):
listener = bind_listener(("127.0.0.1", free_port), STRICT)
try:
assert listener.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 0
finally:
listener.close()
def test_reuseaddr_does_not_allow_a_second_listener(free_port):
first = bind_listener(("127.0.0.1", free_port), SERVICE)
try:
with pytest.raises(OSError) as caught:
bind_listener(("127.0.0.1", free_port), SERVICE)
assert caught.value.errno == errno.EADDRINUSE
finally:
first.close()
def test_reuseport_allows_a_second_listener(free_port):
first = bind_listener(("127.0.0.1", free_port), FLEET)
second = bind_listener(("127.0.0.1", free_port), FLEET)
try:
assert first.getsockname() == second.getsockname()
finally:
first.close()
second.close()
def test_reuseport_against_a_plain_listener_fails(free_port):
first = bind_listener(("127.0.0.1", free_port), SERVICE)
try:
with pytest.raises(OSError) as caught:
bind_listener(("127.0.0.1", free_port), FLEET)
assert caught.value.errno == errno.EADDRINUSE
finally:
first.close()
def test_a_failed_bind_closes_its_socket(held_port):
port, _ = held_port
before = fds()
with pytest.raises(OSError):
bind_listener(("127.0.0.1", port), SERVICE)
assert fds() == before
def test_apply_sets_both_flags(free_port):
sock = apply(socket.socket(), FLEET)
try:
assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1
assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1
finally:
sock.close()
def test_policies_are_named_and_frozen():
for policy in (SERVICE, FLEET, CLIENT, STRICT):
assert isinstance(policy, Policy)
assert policy.name
with pytest.raises(Exception):
SERVICE.name = "other" # type: ignore[misc]
def test_bind_client_source_connects(free_port):
listener = bind_listener(("127.0.0.1", free_port), STRICT)
sock = bind_client_source(("127.0.0.1", 0), ("127.0.0.1", free_port))
try:
accepted, _ = listener.accept()
assert sock.getsockname()[1] != 0
accepted.close()
finally:
sock.close()
listener.close()
def test_bind_client_source_closes_on_failure(free_port):
before = fds()
with pytest.raises(OSError):
bind_client_source(("127.0.0.1", 0), ("127.0.0.1", free_port), timeout_s=0.5)
assert fds() == before
Hex ports, an IPv6 line, state codes, and a file that is not there. test_table.py
"""Reading the socket tables: hex ports, state codes, IPv6 lines, and a file that is not there."""
from __future__ import annotations
import pathlib
from portguard import table
HEADER = (" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid "
"timeout inode")
LISTEN = (" 0: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 "
"1000 0 1 1 0000000000000000 100 0 0 10 0")
TIME_WAIT = (" 1: 0100007F:1F90 0100007F:C350 06 00000000:00000000 03:00000E57 00000000 "
"1000 0 0 3 0000000000000000")
ESTABLISHED = (" 2: 0100007F:1F90 0100007F:C351 01 00000000:00000000 00:00000000 00000000 "
"1000 0 0 4 0000000000000000 20 4 30 10 -1")
NOT_A_SOCKET = "this line is not a socket"
# A /proc/net/tcp6 line: the address is 32 hex characters, the port after the last colon, and the
# state in the same fourth field as the IPv4 file.
IPV6_LISTEN = (" 0: 00000000000000000000000001000000:1F90 "
"00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 "
"00000000 1000 0 12345 1 0000000000000000 100 0 0 10 0")
IPV6_TIME_WAIT = (" 1: 00000000000000000000000001000000:1F90 "
"00000000000000000000000001000000:D431 06 00000000:00000000 03:00000E57 "
"00000000 1000 0 0 3 0000000000000000")
def test_local_port_reads_hex():
assert table.local_port(LISTEN) == 8080
assert table.local_port(TIME_WAIT) == 8080
def test_local_port_reads_an_ipv6_line():
assert table.local_port(IPV6_LISTEN) == 8080
assert table.local_port(IPV6_TIME_WAIT) == 8080
def test_local_port_rejects_a_non_socket_line():
assert table.local_port(NOT_A_SOCKET) is None
assert table.local_port(HEADER) is None
def test_local_port_rejects_a_bad_hex_port():
assert table.local_port("1: 0100007F:ZZZZ 00000000:0000 0A") is None
def test_state_code_reads_the_fourth_field():
assert table.state_code(LISTEN) == "0A"
assert table.state_code(TIME_WAIT) == "06"
assert table.state_code(ESTABLISHED) == "01"
assert table.state_code(IPV6_LISTEN) == "0A"
def test_state_code_rejects_an_unknown_code():
assert table.state_code("1: 0100007F:1F90 00000000:0000 7F 00:00 00:00 00 1000 0 0") is None
def test_parse_skips_the_header():
entries = table.parse("\n".join([HEADER, LISTEN, TIME_WAIT]))
assert entries == [{"local_port": 8080, "state": "LISTEN"},
{"local_port": 8080, "state": "TIME_WAIT"}]
def test_parse_of_an_empty_file_is_empty():
assert table.parse("") == []
assert table.parse(HEADER) == []
def test_states_for_port_counts_each_state():
text = "\n".join([HEADER, LISTEN, TIME_WAIT, TIME_WAIT, ESTABLISHED])
counts = table.states_for_port(8080, text)
assert counts == {"LISTEN": 1, "TIME_WAIT": 2, "ESTABLISHED": 1}
def test_states_for_port_ignores_another_port():
text = "\n".join([HEADER, LISTEN])
assert table.states_for_port(1, text) == {}
def test_a_port_listed_by_both_files_is_counted_from_both():
both = "\n".join([HEADER, LISTEN, IPV6_LISTEN, IPV6_TIME_WAIT])
assert table.states_for_port(8080, both) == {"LISTEN": 2, "TIME_WAIT": 1}
def test_the_two_paths_are_both_named():
assert [path.name for path in table.TABLE_PATHS] == ["tcp", "tcp6"]
def test_table_text_skips_a_file_that_is_not_there(tmp_path):
present = tmp_path / "tcp"
present.write_text("\n".join([HEADER, LISTEN]), encoding="utf-8")
text = table.table_text((present, tmp_path / "tcp6"))
assert table.states_for_port(8080, text) == {"LISTEN": 1}
assert table.table_text((tmp_path / "tcp6",)) == ""
def test_time_wait_count_reads_only_time_wait():
text = "\n".join([HEADER, TIME_WAIT, ESTABLISHED])
assert table.time_wait_count(8080, text) == 1
assert table.time_wait_count(1, text) == 0
def test_the_real_table_parses():
entries = table.parse(pathlib.Path("/proc/net/tcp").read_text(encoding="utf-8"))
assert isinstance(entries, list)
for entry in entries:
assert 0 < entry["local_port"] < 65536
assert entry["state"] in table.STATE_NAMES.values()
def test_state_names_cover_the_code_that_matters():
assert table.STATE_NAMES[table.TIME_WAIT] == "TIME_WAIT"
assert table.STATE_NAMES["0A"] == "LISTEN"
A free port now, a held port until the timeout, and a plain bind by default. test_wait.py
"""Waiting for a port: a free one now, a held one until the timeout, and an entry the flag skips."""
from __future__ import annotations
import socket
import time
from portguard.reuse import SERVICE
from portguard.wait import WaitResult, can_bind, wait_for_bind
def leave_time_wait(port: int) -> None:
"""One TIME_WAIT entry on the port, left by a socket that had SO_REUSEADDR set."""
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", port))
listener.listen(4)
client = socket.create_connection(("127.0.0.1", port))
server, _ = listener.accept()
server.close()
time.sleep(0.05)
client.close()
listener.close()
time.sleep(0.05)
def test_can_bind_a_free_port(free_port):
assert can_bind(("127.0.0.1", free_port)) is True
def test_cannot_bind_a_held_port(held_port):
port, _ = held_port
assert can_bind(("127.0.0.1", port)) is False
def test_can_bind_leaves_no_socket_behind(held_port):
port, _ = held_port
for _ in range(20):
can_bind(("127.0.0.1", port))
assert can_bind(("127.0.0.1", port)) is False
def test_wait_for_bind_returns_at_once_on_a_free_port(free_port):
result = wait_for_bind(("127.0.0.1", free_port), timeout_s=1.0, interval_s=0.05)
assert isinstance(result, WaitResult)
assert result.bound is True
assert result.attempts == 1
assert result.seconds < 1.0
def test_wait_for_bind_times_out_on_a_held_port(held_port):
port, _ = held_port
started = time.monotonic()
result = wait_for_bind(("127.0.0.1", port), timeout_s=0.3, interval_s=0.05)
elapsed = time.monotonic() - started
assert result.bound is False
assert result.attempts > 1
assert result.seconds >= 0.3
assert elapsed >= 0.3
def test_wait_for_bind_honours_the_policy(free_port):
result = wait_for_bind(("127.0.0.1", free_port), timeout_s=1.0, interval_s=0.05,
policy=SERVICE)
assert result.bound is True
def test_wait_result_is_frozen():
result = WaitResult(0.0, 1, True)
assert result.bound is True
try:
result.bound = False # type: ignore[misc]
except Exception as caught: # noqa: BLE001 - the point is that it raises
assert caught is not None
else:
raise AssertionError("WaitResult allowed a change")
def test_a_plain_bind_is_the_default(free_port):
"""The waiter must not set the flag it is waiting for, or it never waits for it."""
leave_time_wait(free_port)
assert can_bind(("127.0.0.1", free_port)) is False
assert can_bind(("127.0.0.1", free_port), SERVICE) is True
