linera_base/
port.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Functionality for obtaining some free port.
5
6use anyhow::{bail, Result};
7use port_selector::random_free_tcp_port;
8
9use crate::time::Duration;
10
11/// Provides a port that is currently not used
12pub async fn get_free_port() -> Result<u16> {
13    for i in 1..10 {
14        let port = random_free_tcp_port();
15        if let Some(port) = port {
16            return Ok(port);
17        }
18        crate::time::timer::sleep(Duration::from_secs(i)).await;
19    }
20    bail!("Failed to obtain a port");
21}
22
23/// Provides a local endpoint that is currently available
24pub async fn get_free_endpoint() -> Result<String> {
25    let port = get_free_port().await?;
26    Ok(format!("127.0.0.1:{}", port))
27}