Port collisions in tests—when multiple tests spin up servers and accidentally pick the same port—are a common source of flakiness. Random port selection reduces but doesn't eliminate collisions, and sequential port incrementing creates its own problems. The reliable solution is binding to port 0, which asks the OS kernel to assign a free ephemeral port from its managed range (e.g., 32768–60999 on Linux). After binding, `getsockname()` retrieves the actual assigned port so requests can be directed to it. A Rust/Tokio example demonstrates the pattern: bind a `TcpListener` to port 0, call `local_addr()` to get the assigned address, and pass it to the test client.

6m read timeFrom ntietz.com
Post cover image
Table of contents
Can we pick a random port?Incremental ports?Sooooo ephemeral ports from the kernel?

Sort: