diff --git a/crates/nu-command/src/network/port.rs b/crates/nu-command/src/network/port.rs index 64df0047a..5d0a53a4a 100644 --- a/crates/nu-command/src/network/port.rs +++ b/crates/nu-command/src/network/port.rs @@ -101,15 +101,17 @@ fn get_free_port( } // try given port one by one. - let addrs: Vec = (start_port..=end_port) - .map(|current| { - SocketAddr::V4(SocketAddrV4::new( - Ipv4Addr::new(127, 0, 0, 1), - current as u16, - )) - }) - .collect(); - TcpListener::bind(addrs.as_slice())? + match (start_port..=end_port) + .map(|port| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port as u16))) + .find_map(|addr| TcpListener::bind(addr).ok()) + { + Some(listener) => listener, + None => { + return Err(ShellError::IOError { + msg: "Every port has been tried, but no valid one was found".to_string(), + }) + } + } }; let free_port = listener.local_addr()?.port(); diff --git a/crates/nu-command/tests/commands/network/port.rs b/crates/nu-command/tests/commands/network/port.rs index f9c739a27..d5921face 100644 --- a/crates/nu-command/tests/commands/network/port.rs +++ b/crates/nu-command/tests/commands/network/port.rs @@ -30,7 +30,10 @@ fn port_with_already_usage() { handler.join().unwrap(); // check for error kind str. - if actual.err.contains("AddrInUse") { + if actual + .err + .contains("Every port has been tried, but no valid one was found") + { return; } }