Skip to main content

rtci_mdns/
socket.rs

1//! Socket utilities for mDNS.
2//!
3//! This module provides [`MulticastSocket`], a builder for creating properly
4//! configured UDP sockets for mDNS communication.
5//!
6//! # Example
7//!
8//! ```rust,ignore
9//! use rtci_mdns::MulticastSocket;
10//! use std::net::SocketAddr;
11//!
12//! let bind_addr: SocketAddr = "0.0.0.0:5353".parse().unwrap();
13//! let std_socket = MulticastSocket::new(bind_addr).into_std()?;
14//!
15//! // For tokio:
16//! let socket = tokio::net::UdpSocket::from_std(std_socket)?;
17//! ```
18
19use std::io;
20use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
21
22use crate::MDNS_PORT;
23use crate::proto::MDNS_MULTICAST_IPV4;
24use socket2::{Domain, Protocol, Socket, Type};
25
26/// The IP TTL mDNS packets are sent with (RFC 6762 section 11): older queriers take any
27/// other value for a packet from off the link and drop it.
28const MDNS_IP_TTL: u32 = 255;
29
30/// Sets the TTL of what `socket` sends, multicast and unicast, to [`MDNS_IP_TTL`]. The
31/// operating system's default for multicast is 1.
32fn set_mdns_ttl(socket: &Socket) -> io::Result<()> {
33    socket.set_multicast_ttl_v4(MDNS_IP_TTL)?;
34    socket.set_ttl_v4(MDNS_IP_TTL)
35}
36
37/// A builder for creating multicast UDP sockets suitable for mDNS.
38///
39/// `MulticastSocket` provides a convenient way to create properly configured
40/// UDP sockets for mDNS communication. The resulting socket will be:
41///
42/// - Bound to the specified address (typically `0.0.0.0:5353`)
43/// - Configured with `SO_REUSEADDR` enabled
44/// - Configured with `SO_REUSEPORT` enabled (on supported platforms)
45/// - Set to non-blocking mode for async compatibility
46/// - Joined to the mDNS multicast group (224.0.0.251)
47/// - Sending with IP TTL 255, multicast and unicast (RFC 6762 section 11)
48///
49/// # Examples
50///
51/// Basic usage with tokio:
52///
53/// ```rust,ignore
54/// use rtci_mdns::MulticastSocket;
55/// use std::net::SocketAddr;
56///
57/// let bind_addr: SocketAddr = "0.0.0.0:5353".parse().unwrap();
58/// let std_socket = MulticastSocket::new(bind_addr).into_std()?;
59/// let socket = tokio::net::UdpSocket::from_std(std_socket)?;
60/// ```
61///
62/// With a specific network interface:
63///
64/// ```rust,ignore
65/// use rtci_mdns::MulticastSocket;
66/// use std::net::{Ipv4Addr, SocketAddr};
67///
68/// let bind_addr: SocketAddr = "0.0.0.0:5353".parse().unwrap();
69/// let interface = Ipv4Addr::new(192, 168, 1, 100);
70/// let std_socket = MulticastSocket::new(bind_addr)
71///     .with_interface(interface)
72///     .into_std()?;
73/// ```
74#[derive(Debug, Clone)]
75pub struct MulticastSocket {
76    multicast_local_ipv4: Option<Ipv4Addr>,
77    multicast_local_port: Option<u16>,
78    interface: Option<Ipv4Addr>,
79}
80
81impl Default for MulticastSocket {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl MulticastSocket {
88    /// Creates a new `MulticastSocket` builder with the specified bind address.
89    ///
90    /// # Arguments
91    ///
92    /// * `bind_addr` - The local address to bind to. Use `0.0.0.0:5353` to listen
93    ///   on all interfaces on the standard mDNS port.
94    ///
95    /// # Example
96    ///
97    /// ```rust
98    /// use rtci_mdns::MulticastSocket;
99    ///
100    /// let builder = MulticastSocket::new();
101    /// ```
102    pub fn new() -> Self {
103        Self {
104            multicast_local_ipv4: None,
105            multicast_local_port: None,
106            interface: None,
107        }
108    }
109
110    /// Sets the local IPv4 address to bind the multicast socket to.
111    ///
112    /// Defaults to unspecified (`0.0.0.0`), letting the OS choose.
113    pub fn with_multicast_local_ipv4(mut self, multicast_local_ipv4: Ipv4Addr) -> Self {
114        self.multicast_local_ipv4 = Some(multicast_local_ipv4);
115        self
116    }
117
118    /// Sets the local port to bind the multicast socket to.
119    ///
120    /// Defaults to the mDNS port (5353), which is required to receive multicast queries
121    /// from other hosts; a different port is only useful for testing.
122    pub fn with_multicast_local_port(mut self, multicast_local_port: u16) -> Self {
123        self.multicast_local_port = Some(multicast_local_port);
124        self
125    }
126
127    /// Sets a specific network interface for multicast operations.
128    ///
129    /// If not set, the socket joins the multicast group on all interfaces
130    /// (`INADDR_ANY`).
131    ///
132    /// With an interface the socket also sends by it (`IP_MULTICAST_IF`, RFC 6762 section 14).
133    /// Without one, on Linux, macOS and other systems, it sends by the system's route for
134    /// 224.0.0.251. On Windows that route comes from the destination cache, and a process that
135    /// sent to the group from 127.0.0.1 leaves it on loopback after it exits, so on Windows a
136    /// socket built without an interface (and without a local address of its own,
137    /// [`with_multicast_local_ipv4`](Self::with_multicast_local_ipv4)) joins and sends on the
138    /// interface of the default route instead (see [`into_std`](Self::into_std)). On a Windows host with
139    /// several interfaces whose mDNS link is not the default route's, pass the interface of
140    /// the address the application publishes.
141    ///
142    /// # Arguments
143    ///
144    /// * `interface` - The IPv4 address of the network interface to use.
145    ///
146    /// # Example
147    ///
148    /// ```rust
149    /// use rtci_mdns::MulticastSocket;
150    /// use std::net::Ipv4Addr;
151    ///
152    /// let builder = MulticastSocket::new()
153    ///     .with_interface(Ipv4Addr::new(192, 168, 1, 100));
154    /// ```
155    pub fn with_interface(mut self, interface: Ipv4Addr) -> Self {
156        self.interface = Some(interface);
157        self
158    }
159
160    /// Converts this builder into a configured `std::net::UdpSocket`.
161    ///
162    /// This method creates the socket with the following configuration:
163    /// - `SO_REUSEADDR` enabled (allows multiple processes to bind)
164    /// - `SO_REUSEPORT` enabled on Unix platforms (except Solaris/illumos)
165    /// - Non-blocking mode enabled (for async compatibility)
166    /// - Joined to the mDNS multicast group (224.0.0.251), on [`with_interface`]'s interface when
167    ///   one is given, and sending by that interface (`IP_MULTICAST_IF`), whatever the system's
168    ///   route for the group says
169    /// - Without an interface: on Windows, unless [`with_multicast_local_ipv4`] names a local
170    ///   address, joined and sending on the interface of the default route (the address a UDP
171    ///   socket connected to 192.0.2.1, a documentation address, takes; nothing is sent there),
172    ///   as if [`with_interface`] had named it: the system's route for the group, which both a
173    ///   join on `INADDR_ANY` and a send without `IP_MULTICAST_IF` follow there, is left on
174    ///   loopback for the whole host by any process that sent to the group from 127.0.0.1.
175    ///   Where the default route's address is unspecified or loopback, or there is none, and on
176    ///   other systems: joined on the default interface (`INADDR_ANY`), sending by the system's
177    ///   route for the group
178    /// - IP TTL 255 on what it sends (RFC 6762 section 11)
179    ///
180    /// [`with_interface`]: Self::with_interface
181    /// [`with_multicast_local_ipv4`]: Self::with_multicast_local_ipv4
182    ///
183    /// # Errors
184    ///
185    /// Returns an error if:
186    /// - Socket creation fails
187    /// - Setting socket options fails
188    /// - Binding to the address fails
189    /// - Joining the multicast group fails
190    ///
191    /// # Example
192    ///
193    /// ```rust,ignore
194    /// use rtci_mdns::MulticastSocket;
195    /// use std::net::SocketAddr;
196    ///
197    /// let bind_addr: SocketAddr = "0.0.0.0:5353".parse().unwrap();
198    /// let std_socket = MulticastSocket::new(bind_addr).into_std()?;
199    ///
200    /// // Use with tokio:
201    /// let socket = tokio::net::UdpSocket::from_std(std_socket)?;
202    /// ```
203    ///
204    /// # Platform Notes
205    ///
206    /// - On Unix-like systems (except Solaris/illumos), `SO_REUSEPORT` is enabled
207    ///   to allow multiple processes to bind to the same port.
208    pub fn into_std(self) -> io::Result<UdpSocket> {
209        let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
210
211        // Enable address reuse for multiple processes
212        socket.set_reuse_address(true)?;
213
214        // Enable port reuse on supported platforms
215        #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
216        socket.set_reuse_port(true)?;
217
218        // Set non-blocking mode for async compatibility
219        socket.set_nonblocking(true)?;
220
221        // RFC 6762 section 11: responses leave with IP TTL 255
222        set_mdns_ttl(&socket)?;
223
224        let multicast_local_ip = if let Some(multicast_local_ipv4) = self.multicast_local_ipv4 {
225            IpAddr::V4(multicast_local_ipv4)
226        } else if cfg!(target_os = "linux") {
227            IpAddr::V4(MDNS_MULTICAST_IPV4)
228        } else {
229            // DNS_MULTICAST_IPV4 doesn't work on Mac/Win,
230            // only 0.0.0.0 works fine, even 127.0.0.1 doesn't work
231            IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))
232        };
233
234        let multicast_local_port = if let Some(multicast_local_port) = self.multicast_local_port {
235            multicast_local_port
236        } else {
237            MDNS_PORT
238        };
239
240        let multicast_local_addr = SocketAddr::new(multicast_local_ip, multicast_local_port);
241
242        // Bind to the specified address
243        socket.bind(&multicast_local_addr.into())?;
244
245        // RFC 6762 section 14: the socket joins the group on the interface it sends by, and what
246        // it sends leaves by that interface (`IP_MULTICAST_IF`), not by the system's route for
247        // the group. On Windows that route comes from the destination cache, which a process
248        // that sent to the group from loopback leaves on loopback after it has exited (source
249        // 127.0.0.1, `netsh interface ipv4 show destinationcache`): a socket without
250        // `IP_MULTICAST_IF` then sends by loopback with source 127.0.0.1, and a join on
251        // `INADDR_ANY` lands on loopback too (agent-test run 46123619860: a socket joined on
252        // `INADDR_ANY` and sending by the network interface no longer heard its own datagrams).
253        // So without an interface, on Windows, the socket joins and sends on the default route's
254        // interface (`multicast_if`). Elsewhere it keeps `INADDR_ANY` and the system's route
255        // (GitHub's macOS image routes the group to lo0 on purpose).
256        let bound_unspecified = self
257            .multicast_local_ipv4
258            .is_none_or(|ip| ip.is_unspecified());
259        let iface = multicast_if(
260            self.interface,
261            cfg!(windows) && bound_unspecified,
262            default_route_v4,
263        );
264        socket.join_multicast_v4(
265            &MDNS_MULTICAST_IPV4,
266            &iface.unwrap_or(Ipv4Addr::UNSPECIFIED),
267        )?;
268        if let Some(iface) = iface {
269            socket.set_multicast_if_v4(&iface)?;
270        }
271
272        Ok(socket.into())
273    }
274}
275
276/// The interface a socket joins the group on and its multicast leaves by (`IP_MULTICAST_IF`), or
277/// `None` for `INADDR_ANY` and the system's route for the group: the interface given; without one, where `default_route_instead` (on
278/// Windows, a socket bound to the unspecified address), the default route's
279/// ([`default_route_v4`]) unless that is unspecified or loopback.
280fn multicast_if(
281    interface: Option<Ipv4Addr>,
282    default_route_instead: bool,
283    default_route: impl FnOnce() -> Option<Ipv4Addr>,
284) -> Option<Ipv4Addr> {
285    match interface {
286        Some(interface) if !interface.is_unspecified() => Some(interface),
287        _ if default_route_instead => {
288            default_route().filter(|ip| !ip.is_unspecified() && !ip.is_loopback())
289        }
290        _ => None,
291    }
292}
293
294/// The address of the host's default-route IPv4 interface: the local address a UDP socket
295/// connected to 192.0.2.1:9 (TEST-NET-1, RFC 5737) takes. Connecting a UDP socket sends nothing.
296/// `None` without an IPv4 default route. Not the route for 224.0.0.251, which is what a stale
297/// destination-cache entry moves on Windows.
298fn default_route_v4() -> Option<Ipv4Addr> {
299    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;
300    socket.connect((Ipv4Addr::new(192, 0, 2, 1), 9)).ok()?;
301    match socket.local_addr().ok()?.ip() {
302        IpAddr::V4(ip) => Some(ip),
303        IpAddr::V6(_) => None,
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::proto::MDNS_PORT;
311    use std::str::FromStr;
312
313    #[test]
314    fn test_multicast_constants() {
315        assert_eq!(MDNS_MULTICAST_IPV4, Ipv4Addr::new(224, 0, 0, 251));
316        assert_eq!(MDNS_PORT, 5353);
317    }
318
319    #[test]
320    fn test_multicast_socket_builder() {
321        let builder = MulticastSocket::new()
322            .with_multicast_local_ipv4(Ipv4Addr::from_str("0.0.0.0").unwrap())
323            .with_multicast_local_port(5353);
324        assert!(builder.multicast_local_ipv4.is_some());
325        assert!(builder.multicast_local_port.is_some());
326        assert!(builder.interface.is_none());
327    }
328
329    #[test]
330    fn test_multicast_socket_with_interface() {
331        let interface = Ipv4Addr::new(192, 168, 1, 100);
332        let builder = MulticastSocket::new()
333            .with_multicast_local_ipv4(Ipv4Addr::from_str("0.0.0.0").unwrap())
334            .with_multicast_local_port(5353)
335            .with_interface(interface);
336        assert_eq!(builder.interface, Some(interface));
337    }
338
339    // RFC 6762 section 11. The socket is neither bound nor used: only its options are read.
340    #[test]
341    fn test_mdns_socket_sends_with_ip_ttl_255() {
342        let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP)).unwrap();
343        assert_ne!(socket.multicast_ttl_v4().unwrap(), 255, "not the default");
344        set_mdns_ttl(&socket).unwrap();
345        assert_eq!(socket.multicast_ttl_v4().unwrap(), 255);
346        assert_eq!(socket.ttl_v4().unwrap(), 255);
347    }
348
349    const NIC: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 49);
350
351    // RFC 6762 section 14: an interface given is the one sent by, on every platform; the default
352    // route is not even asked.
353    #[test]
354    fn an_interface_given_is_the_one_multicast_leaves_by() {
355        let given = Ipv4Addr::new(192, 168, 1, 100);
356        for default_route_instead in [false, true] {
357            assert_eq!(
358                multicast_if(Some(given), default_route_instead, || panic!("not asked")),
359                Some(given)
360            );
361        }
362    }
363
364    // On Windows (`default_route_instead`) a socket without an interface sends by the default
365    // route's interface, not by the group's route that a stale destination-cache entry leaves on
366    // loopback; elsewhere it follows the system's route (`None`).
367    #[test]
368    fn without_an_interface_windows_sends_by_the_default_route_and_others_by_the_group_route() {
369        assert_eq!(multicast_if(None, true, || Some(NIC)), Some(NIC));
370        assert_eq!(
371            multicast_if(Some(Ipv4Addr::UNSPECIFIED), true, || Some(NIC)),
372            Some(NIC)
373        );
374        assert_eq!(multicast_if(None, false, || panic!("not asked")), None);
375    }
376
377    // A default route that is loopback or unspecified, or none, leaves the system's route.
378    #[test]
379    fn a_default_route_on_loopback_or_none_leaves_the_system_route() {
380        assert_eq!(multicast_if(None, true, || Some(Ipv4Addr::LOCALHOST)), None);
381        assert_eq!(
382            multicast_if(None, true, || Some(Ipv4Addr::UNSPECIFIED)),
383            None
384        );
385        assert_eq!(multicast_if(None, true, || None), None);
386    }
387
388    // Note: Socket creation tests would require actual network access
389    // and might conflict with other mDNS services, so we keep them minimal
390}