embedded_nal/
dns.rs

1use core::net::IpAddr;
2
3/// This is the host address type to be returned by `gethostbyname`.
4///
5/// An IPv4 address type always looks for `A` records, while IPv6 address type
6/// will look for `AAAA` records
7#[derive(Clone, Debug, PartialEq)]
8pub enum AddrType {
9	/// Result is `A` record
10	IPv4,
11	/// Result is `AAAA` record
12	IPv6,
13	/// Result is either a `A` record, or a `AAAA` record
14	Either,
15}
16
17/// This trait is an extension trait for [`TcpStack`] and [`UdpStack`] for dns
18/// resolutions. It does not handle every DNS record type, but is meant as an
19/// embedded alternative to [`ToSocketAddrs`], and is as such meant to resolve
20/// an ip address from a hostname, or a hostname from an ip address. This means
21/// that it only deals in host address records `A` (IPv4) and `AAAA` (IPv6).
22///
23/// [`TcpStack`]: crate::trait@TcpStack
24/// [`UdpStack`]: crate::trait@UdpStack
25/// [`ToSocketAddrs`]:
26/// https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html
27pub trait Dns {
28	/// The type returned when we have an error
29	type Error: core::fmt::Debug;
30
31	/// Resolve the first ip address of a host, given its hostname and a desired
32	/// address record type to look for
33	fn get_host_by_name(
34		&mut self,
35		hostname: &str,
36		addr_type: AddrType,
37	) -> nb::Result<IpAddr, Self::Error>;
38
39	/// Resolve the hostname of a host, given its ip address.
40	///
41	/// The hostname is stored at the beginning of `result`, the length is returned.
42	///
43	/// If the buffer is too small to hold the domain name, an error should be returned.
44	///
45	/// **Note**: A fully qualified domain name (FQDN), has a maximum length of
46	/// 255 bytes according to [`rfc1035`]. Therefore, you can pass a 255-byte long
47	/// buffer to guarantee it'll always be large enough.
48	///
49	/// [`rfc1035`]: https://tools.ietf.org/html/rfc1035
50	fn get_host_by_address(
51		&mut self,
52		addr: IpAddr,
53		result: &mut [u8],
54	) -> nb::Result<usize, Self::Error>;
55}
56
57impl<T: Dns> Dns for &mut T {
58	type Error = T::Error;
59
60	fn get_host_by_name(
61		&mut self,
62		hostname: &str,
63		addr_type: AddrType,
64	) -> nb::Result<IpAddr, Self::Error> {
65		T::get_host_by_name(self, hostname, addr_type)
66	}
67
68	fn get_host_by_address(
69		&mut self,
70		addr: IpAddr,
71		result: &mut [u8],
72	) -> nb::Result<usize, Self::Error> {
73		T::get_host_by_address(self, addr, result)
74	}
75}