Skip to content

Commit 1b7d919

Browse files
committed
Avoid listening port collision by letting OS assing ports
Previously, we could in tests potentially run into listening port collisions resulting into `InvalidSocketAddress` errors. These errors could surface if we rolled port numbers that either collided with other concurrent tests *or* with other unrelated services running on localhost. Here, we simply let the OS assign us a free port number when setting up the testing nodes, which avoids such collisions altoghether (mod the potential TOCTOU race here, which we ignore for now).
1 parent 37045f4 commit 1b7d919

File tree

1 file changed

+6
-10
lines changed

1 file changed

+6
-10
lines changed

tests/common/mod.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -215,22 +215,18 @@ pub(crate) fn random_storage_path() -> PathBuf {
215215
temp_path
216216
}
217217

218-
pub(crate) fn random_port() -> u16 {
219-
let mut rng = rng();
220-
rng.random_range(5000..32768)
221-
}
222-
223218
pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
224219
let num_addresses = 2;
225-
let mut listening_addresses = Vec::with_capacity(num_addresses);
220+
let mut listening_addresses = HashSet::new();
226221

227-
for _ in 0..num_addresses {
228-
let rand_port = random_port();
222+
while listening_addresses.len() < num_addresses {
223+
let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
224+
let rand_port = socket.local_addr().unwrap().port();
229225
let address: SocketAddress = format!("127.0.0.1:{}", rand_port).parse().unwrap();
230-
listening_addresses.push(address);
226+
listening_addresses.insert(address);
231227
}
232228

233-
listening_addresses
229+
listening_addresses.into_iter().collect()
234230
}
235231

236232
pub(crate) fn random_node_alias() -> Option<NodeAlias> {

0 commit comments

Comments
 (0)