simple_mdns/
network_scope.rs

1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
2
3pub const MULTICAST_PORT: u16 = 5353;
4pub const MULTICAST_ADDR_IPV4: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
5pub const MULTICAST_ADDR_IPV6: Ipv6Addr = Ipv6Addr::new(0xFF02, 0, 0, 0, 0, 0, 0, 0xFB);
6
7/// Network scope to be used by service discovery
8/// Default scope for services is to use IPV4 protocol
9#[derive(Debug, Copy, Clone)]
10pub enum NetworkScope {
11    /// Uses IPV4 protocol with UNSPECIFIED network interface (0.0.0.0)
12    V4,
13    /// Uses IPV4 protocol and provided network interface
14    V4WithInterface(Ipv4Addr),
15    /// Uses IPV6 protocol with UNSPECIFIED network interface (0)
16    V6,
17    /// Uses IPV6 protocol with provided network interface
18    V6WithInterface(u32),
19}
20
21impl NetworkScope {
22    /// Returns `true` if the network scope is [`V4`] or [`V4WithInterface`].
23    ///
24    /// [`V4`]: NetworkScope::V4
25    /// [`V4WithInterface`]: NetworkScope::V4WithInterface
26    #[must_use]
27    pub fn is_v4(&self) -> bool {
28        matches!(&self, Self::V4 | Self::V4WithInterface(..))
29    }
30
31    /// Gets de socket address for the network scope.
32    pub fn socket_address(&self) -> SocketAddr {
33        if self.is_v4() {
34            SocketAddr::new(IpAddr::V4(MULTICAST_ADDR_IPV4), MULTICAST_PORT)
35        } else {
36            SocketAddr::new(IpAddr::V6(MULTICAST_ADDR_IPV6), MULTICAST_PORT)
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_ipv4_multicast() {
47        assert!(MULTICAST_ADDR_IPV4.is_multicast());
48    }
49
50    #[test]
51    fn test_ipv6_multicast() {
52        assert!(MULTICAST_ADDR_IPV6.is_multicast());
53    }
54}