// 1. The rust standard library uses a backlog of 128 for TCP sockets. This matches `SOMAXCONN` on
// 2. Mio (backend for tokio) previously used 1024. But they recently (confusingly) copied the logic
// 3. Tor first tries using `INT_MAX`, and if that fails falls back to `SOMAXCONN` (using a global
// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/listen.2.html
// 5. While the rust APIs take a `u32`, the libc API uses `int`. So we shouldn't use a value larger
// 6. We should be careful not to set this too large, as supposedly some systems will truncate this to
// 16 bits. So for example a value of `65536` would cause a backlog of 1. But maybe they are just
// Here we use `u16::MAX`. We assume that this will succeed on all supported platforms. Unlike tor,
// we do not try again with a smaller value since this doesn't seem to be needed on modern systems.
// A value of `u16::MAX` is arguably too high, since a smaller value like 4096 would be large enough
/// The socket will be non-blocking, and the socket handle will be close-on-exec/non-inheritable.
/// Historically we relied on the runtime to create a listening socket, but we need some specific
/// socket options set, and not all runtimes will behave the same. It's better for us to create the
/// socket with the options we need and with consistent behaviour across all runtimes. For example
/// if each runtime were using a different `listen()` backlog size, it might be difficult to debug
pub(crate) fn tcp_listen(addr: &std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
// Below we try to match what a `tokio::net::TcpListener::bind()` would do. This is a bit tricky
// > // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse