Skip to main content

drogue_network/
addr.rs

1pub use no_std_net::{
2    IpAddr,
3    Ipv4Addr,
4    Ipv6Addr,
5    SocketAddr,
6    SocketAddrV4,
7    SocketAddrV6,
8};
9
10use heapless::{
11    String,
12    consts::U256,
13};
14use core::str::FromStr;
15
16#[derive(Debug)]
17pub struct HostAddr {
18    ip: IpAddr,
19    hostname: Option<String<U256>>,
20}
21
22impl HostAddr {
23    pub fn new(ip: IpAddr, hostname: Option<String<U256>>) -> Self {
24        HostAddr {
25            ip,
26            hostname,
27        }
28    }
29
30    pub fn ipv4(octets: [u8;4]) -> HostAddr {
31        HostAddr {
32            ip: IpAddr::from(octets),
33            hostname: None
34        }
35    }
36
37    pub fn ipv6(octets: [u8;16]) -> HostAddr {
38        HostAddr {
39            ip: IpAddr::from(octets),
40            hostname: None
41        }
42    }
43
44    pub fn ip(&self) -> IpAddr {
45        self.ip
46    }
47
48    pub fn hostname(&self) -> Option<&String<U256>> {
49        self.hostname.as_ref()
50    }
51}
52
53#[derive(Debug)]
54pub struct AddrParseError;
55
56impl FromStr for HostAddr {
57    type Err = AddrParseError;
58
59    fn from_str(s: &str) -> Result<Self, Self::Err> {
60        Ok(HostAddr::new(
61            IpAddr::from_str(s).map_err(|_| AddrParseError)?,
62            Some(String::from_str(s).unwrap()),
63        ))
64    }
65}
66
67impl From<IpAddr> for HostAddr {
68    fn from(ip: IpAddr) -> Self {
69        HostAddr {
70            ip,
71            hostname: None,
72        }
73    }
74}
75
76#[derive(Debug)]
77pub struct HostSocketAddr {
78    addr: HostAddr,
79    port: u16,
80}
81
82impl HostSocketAddr {
83    pub fn new(addr: HostAddr, port: u16) -> HostSocketAddr {
84        HostSocketAddr {
85            addr,
86            port,
87        }
88    }
89
90    pub fn from(addr: &str, port: u16) -> Result<HostSocketAddr, AddrParseError> {
91        Ok( Self::new(
92            HostAddr::from_str(addr)?,
93            port
94        ) )
95    }
96
97    pub fn addr(&self) -> &HostAddr {
98        &self.addr
99    }
100
101    pub fn port(&self) -> u16 {
102        self.port
103    }
104
105    pub fn as_socket_addr(&self) -> SocketAddr {
106        SocketAddr::new(self.addr.ip, self.port)
107    }
108}
109