INNER CODE UNIT · Rust
pick_free_port
shenmintao/marginalia · desktop/src-tauri/src/lib.rs:130
fn pick_free_port() -> std::io::Result<u16> {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
drop(listener);
Ok(port)
}
/// Best-effort probe that a configured fixed port is still free before
/// handing it to the sidecar. uvicorn exits immediately on
/// "address already in use" and nothing used to notice — the UI just
/// spun on the health poll forever.
fn port_in_use(host: &str, port: u16) -> bool {
let mut bind_host = host.trim();
if bind_host.is_empty() {
bind_host = "127.0.0.1";
}
let addr = if bind_host.contains(':') && !bind_host.starts_with('[') {
format!("[{}]:{}", bind_host, port)