1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use crate::Result;
use ::std::net::IpAddr;
use ::std::net::Ipv4Addr;
use ::std::net::SocketAddr;

use super::ReservedPort;

pub(crate) const DEFAULT_IP_ADDRESS: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

#[derive(Debug)]
pub struct ReservedSocketAddr {
    reserved_port: ReservedPort,
    socket_addr: SocketAddr,
}

impl ReservedSocketAddr {
    #[must_use]
    pub fn reserve_random_socket_addr() -> Result<Self> {
        let ip_address = DEFAULT_IP_ADDRESS;
        let reserved_port = ReservedPort::random()?;
        let socket_addr = SocketAddr::new(ip_address, reserved_port.port());

        Ok(Self {
            reserved_port,
            socket_addr,
        })
    }

    pub fn port(&self) -> u16 {
        self.reserved_port.port()
    }

    pub fn ip(&self) -> IpAddr {
        self.socket_addr.ip()
    }

    pub fn socket_addr(&self) -> SocketAddr {
        self.socket_addr
    }
}