Class TestPortFactory
PortFactory
(which covers TCP).
The find-then-bind window. Finding a free port means binding port 0, recording
what the OS assigned, then closing the socket so the code under test can bind it. Between the close
and the real bind another process can take the port. Binding the real socket directly is the only
fully race-free option, so callers that can retry on BindException should.
Why these probes deliberately do not set SO_REUSEADDR. PortFactory
sets it on its TCP probes so a caller can re-bind a just-released port without waiting for
TIME_WAIT. That reasoning does not carry over to UDP. On BSD-derived systems (macOS)
two UDP sockets that both set SO_REUSEADDR can bind the same port simultaneously and
silently, with no BindException - datagrams then reach only one of them. Setting it here
would let two concurrent probes "find" the same port and both believe they owned it, manufacturing
the collision this class exists to avoid. Netty's NioDatagramChannel also leaves it off by
default, so a genuine UDP collision surfaces as a BindException rather than as silent
traffic loss. Keep it off.
-
Method Summary
-
Method Details
-
findFreeUdpPort
public static int findFreeUdpPort()Find a free UDP port.A failure to find a port is raised rather than reported as port
0. Returning0silently means "bind an ephemeral port", which for a configuration value such ashttp3Portmeans "feature disabled" - turning an infrastructure failure into a test that quietly skips, or asserts against a server that was never started.- Returns:
- a port number that was free at the moment of probing
- Throws:
IllegalStateException- if no free UDP port could be found
-