Skip to content

Commit

Permalink
Wait for free port in legal range.
Browse files Browse the repository at this point in the history
This issue happens often when I ran the tests locally on my MacOS machine.
  • Loading branch information
nihohit authored and barshaul committed Jun 26, 2024
1 parent 4b18e25 commit 5e8e532
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions redis/tests/support/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,13 +392,19 @@ impl RedisServer {
/// process, so this must be used with care (since here we only use it for tests, it's
/// mostly okay).
pub fn get_random_available_port() -> u16 {
let addr = &"127.0.0.1:0".parse::<SocketAddr>().unwrap().into();
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
socket.set_reuse_address(true).unwrap();
socket.bind(addr).unwrap();
socket.listen(1).unwrap();
let listener = TcpListener::from(socket);
listener.local_addr().unwrap().port()
for _ in 0..10000 {
let addr = &"127.0.0.1:0".parse::<SocketAddr>().unwrap().into();
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
socket.set_reuse_address(true).unwrap();
socket.bind(addr).unwrap();
socket.listen(1).unwrap();
let listener = TcpListener::from(socket);
let port = listener.local_addr().unwrap().port();
if port < 55535 {
return port;
}
}
panic!("Couldn't get a valid port");
}

impl Drop for RedisServer {
Expand Down

0 comments on commit 5e8e532

Please sign in to comment.