Skip to main content

Crate tpt_port_scout

Crate tpt_port_scout 

Source
Expand description

RAII TCP/UDP port reservation for parallel integration tests.

Finding a free port with the classic “bind to :0, read the port, drop the listener, then hand the number to your server” pattern has a TOCTOU race: between dropping the probe listener and your server binding, another process (or another parallel test) can grab the same port.

tpt-port-scout closes that window by keeping the reservation sockets open until you are ready to hand them off. A PortSet binds N listeners on 127.0.0.1:0, exposes each assigned SocketAddr, and only releases the kernel reservations when it is dropped — or when you explicitly convert a listener into a raw handle for your server to reuse.

§Quick start

use tpt_port_scout::PortSet;

// Reserve two free ports; both remain held until `ports` is dropped.
let ports = PortSet::reserve(2).unwrap();
let addr_a = ports.addr(0);
let addr_b = ports.addr(1);
assert_ne!(addr_a.port(), addr_b.port());

§Handing a port off to a server

There are two supported patterns:

  1. Rebind-before-drop (portable, works everywhere). Read addr, then drop the PortSet immediately before your server binds. The race window is as small as possible, but not zero.

  2. Zero-race hand-off (recommended). Convert the reservation listener into a raw OS handle with PortSet::into_std_listener / PortSet::take_listener and let your server adopt the already-bound socket, so the port is never released. See PortSet::take_listener.

This crate has zero runtime dependencies — pure std::net.

Structs§

PortSet
A set of reserved TCP ports on 127.0.0.1.
UdpPortSet
Reserve a set of free UDP ports on 127.0.0.1.