Bind to a random port
1 min read
Binding to 0
assigns you a random port
use std::net::TcpListener;
let listener = TcpListener::bind("localhost:0")?;
println!("{}", listener.local_addr()?.port()); // 51673
conn, _ := net.Listen("tcp", "localhost:0")
fmt.Println(conn.Addr().String()) // 127.0.0.1:51930
Both Rust and Go frameworks support passing that listener to a HTTP server.