Skip to main content

std/os/unix/net/
datagram.rs

1#[cfg(any(
2    target_os = "linux",
3    target_os = "android",
4    target_os = "dragonfly",
5    target_os = "freebsd",
6    target_os = "openbsd",
7    target_os = "netbsd",
8    target_os = "solaris",
9    target_os = "illumos",
10    target_os = "haiku",
11    target_os = "nto",
12    target_os = "qnx",
13    target_os = "cygwin"
14))]
15use libc::MSG_NOSIGNAL;
16
17use super::{SocketAddr, sockaddr_un};
18#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
19use super::{SocketAncillary, recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to};
20#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
21use crate::io::{IoSlice, IoSliceMut};
22use crate::net::Shutdown;
23use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
24use crate::path::Path;
25use crate::sys::net::Socket;
26use crate::sys::{AsInner, FromInner, IntoInner, cvt};
27use crate::time::Duration;
28use crate::{fmt, io};
29#[cfg(not(any(
30    target_os = "linux",
31    target_os = "android",
32    target_os = "dragonfly",
33    target_os = "freebsd",
34    target_os = "openbsd",
35    target_os = "netbsd",
36    target_os = "solaris",
37    target_os = "illumos",
38    target_os = "haiku",
39    target_os = "nto",
40    target_os = "qnx",
41    target_os = "cygwin"
42)))]
43const MSG_NOSIGNAL: core::ffi::c_int = 0x0;
44
45/// A Unix datagram socket.
46///
47/// # Examples
48///
49#[cfg_attr(target_family = "unix", doc = "```no_run")]
50#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
51/// use std::os::unix::net::UnixDatagram;
52///
53/// fn main() -> std::io::Result<()> {
54///     let socket = UnixDatagram::bind("/path/to/my/socket")?;
55///     socket.send_to(b"hello world", "/path/to/other/socket")?;
56///     let mut buf = [0; 100];
57///     let (count, address) = socket.recv_from(&mut buf)?;
58///     println!("socket {:?} sent {:?}", address, &buf[..count]);
59///     Ok(())
60/// }
61/// ```
62#[stable(feature = "unix_socket", since = "1.10.0")]
63pub struct UnixDatagram(Socket);
64
65#[stable(feature = "unix_socket", since = "1.10.0")]
66impl fmt::Debug for UnixDatagram {
67    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
68        let mut builder = fmt.debug_struct("UnixDatagram");
69        builder.field("fd", self.0.as_inner());
70        if let Ok(addr) = self.local_addr() {
71            builder.field("local", &addr);
72        }
73        if let Ok(addr) = self.peer_addr() {
74            builder.field("peer", &addr);
75        }
76        builder.finish()
77    }
78}
79
80impl UnixDatagram {
81    /// Creates a Unix datagram socket bound to the given path.
82    ///
83    /// # Examples
84    ///
85    #[cfg_attr(target_family = "unix", doc = "```no_run")]
86    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
87    /// use std::os::unix::net::UnixDatagram;
88    ///
89    /// let sock = match UnixDatagram::bind("/path/to/the/socket") {
90    ///     Ok(sock) => sock,
91    ///     Err(e) => {
92    ///         println!("Couldn't bind: {e:?}");
93    ///         return
94    ///     }
95    /// };
96    /// ```
97    #[stable(feature = "unix_socket", since = "1.10.0")]
98    pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
99        unsafe {
100            let socket = UnixDatagram::unbound()?;
101            let (addr, len) = sockaddr_un(path.as_ref())?;
102
103            cvt(libc::bind(socket.as_raw_fd(), (&raw const addr) as *const _, len as _))?;
104
105            Ok(socket)
106        }
107    }
108
109    /// Creates a Unix datagram socket bound to an address.
110    ///
111    /// # Examples
112    ///
113    #[cfg_attr(target_family = "unix", doc = "```no_run")]
114    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
115    /// use std::os::unix::net::{UnixDatagram};
116    ///
117    /// fn main() -> std::io::Result<()> {
118    ///     let sock1 = UnixDatagram::bind("path/to/socket")?;
119    ///     let addr = sock1.local_addr()?;
120    ///
121    ///     let sock2 = match UnixDatagram::bind_addr(&addr) {
122    ///         Ok(sock) => sock,
123    ///         Err(err) => {
124    ///             println!("Couldn't bind: {err:?}");
125    ///             return Err(err);
126    ///         }
127    ///     };
128    ///     Ok(())
129    /// }
130    /// ```
131    #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
132    pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixDatagram> {
133        unsafe {
134            let socket = UnixDatagram::unbound()?;
135            cvt(libc::bind(
136                socket.as_raw_fd(),
137                (&raw const socket_addr.addr) as *const _,
138                socket_addr.len as _,
139            ))?;
140            Ok(socket)
141        }
142    }
143
144    /// Creates a Unix Datagram socket which is not bound to any address.
145    ///
146    /// # Examples
147    ///
148    #[cfg_attr(target_family = "unix", doc = "```no_run")]
149    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
150    /// use std::os::unix::net::UnixDatagram;
151    ///
152    /// let sock = match UnixDatagram::unbound() {
153    ///     Ok(sock) => sock,
154    ///     Err(e) => {
155    ///         println!("Couldn't unbound: {e:?}");
156    ///         return
157    ///     }
158    /// };
159    /// ```
160    #[stable(feature = "unix_socket", since = "1.10.0")]
161    pub fn unbound() -> io::Result<UnixDatagram> {
162        let inner = Socket::new(libc::AF_UNIX, libc::SOCK_DGRAM)?;
163        Ok(UnixDatagram(inner))
164    }
165
166    /// Creates an unnamed pair of connected sockets.
167    ///
168    /// Returns two `UnixDatagrams`s which are connected to each other.
169    ///
170    /// # Examples
171    ///
172    #[cfg_attr(target_family = "unix", doc = "```no_run")]
173    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
174    /// use std::os::unix::net::UnixDatagram;
175    ///
176    /// let (sock1, sock2) = match UnixDatagram::pair() {
177    ///     Ok((sock1, sock2)) => (sock1, sock2),
178    ///     Err(e) => {
179    ///         println!("Couldn't unbound: {e:?}");
180    ///         return
181    ///     }
182    /// };
183    /// ```
184    #[stable(feature = "unix_socket", since = "1.10.0")]
185    pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
186        let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
187        Ok((UnixDatagram(i1), UnixDatagram(i2)))
188    }
189
190    /// Connects the socket to the specified path address.
191    ///
192    /// The [`send`] method may be used to send data to the specified address.
193    /// [`recv`] and [`recv_from`] will only receive data from that address.
194    ///
195    /// [`send`]: UnixDatagram::send
196    /// [`recv`]: UnixDatagram::recv
197    /// [`recv_from`]: UnixDatagram::recv_from
198    ///
199    /// # Examples
200    ///
201    #[cfg_attr(target_family = "unix", doc = "```no_run")]
202    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
203    /// use std::os::unix::net::UnixDatagram;
204    ///
205    /// fn main() -> std::io::Result<()> {
206    ///     let sock = UnixDatagram::unbound()?;
207    ///     match sock.connect("/path/to/the/socket") {
208    ///         Ok(sock) => sock,
209    ///         Err(e) => {
210    ///             println!("Couldn't connect: {e:?}");
211    ///             return Err(e)
212    ///         }
213    ///     };
214    ///     Ok(())
215    /// }
216    /// ```
217    #[stable(feature = "unix_socket", since = "1.10.0")]
218    pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
219        unsafe {
220            let (addr, len) = sockaddr_un(path.as_ref())?;
221
222            cvt(libc::connect(self.as_raw_fd(), (&raw const addr) as *const _, len))?;
223        }
224        Ok(())
225    }
226
227    /// Connects the socket to an address.
228    ///
229    /// # Examples
230    ///
231    #[cfg_attr(target_family = "unix", doc = "```no_run")]
232    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
233    /// use std::os::unix::net::{UnixDatagram};
234    ///
235    /// fn main() -> std::io::Result<()> {
236    ///     let bound = UnixDatagram::bind("/path/to/socket")?;
237    ///     let addr = bound.local_addr()?;
238    ///
239    ///     let sock = UnixDatagram::unbound()?;
240    ///     match sock.connect_addr(&addr) {
241    ///         Ok(sock) => sock,
242    ///         Err(e) => {
243    ///             println!("Couldn't connect: {e:?}");
244    ///             return Err(e)
245    ///         }
246    ///     };
247    ///     Ok(())
248    /// }
249    /// ```
250    #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
251    pub fn connect_addr(&self, socket_addr: &SocketAddr) -> io::Result<()> {
252        unsafe {
253            cvt(libc::connect(
254                self.as_raw_fd(),
255                (&raw const socket_addr.addr) as *const _,
256                socket_addr.len,
257            ))?;
258        }
259        Ok(())
260    }
261
262    /// Creates a new independently owned handle to the underlying socket.
263    ///
264    /// The returned `UnixDatagram` is a reference to the same socket that this
265    /// object references. Both handles can be used to accept incoming
266    /// connections and options set on one side will affect the other.
267    ///
268    /// # Examples
269    ///
270    #[cfg_attr(target_family = "unix", doc = "```no_run")]
271    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
272    /// use std::os::unix::net::UnixDatagram;
273    ///
274    /// fn main() -> std::io::Result<()> {
275    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
276    ///     let sock_copy = sock.try_clone().expect("try_clone failed");
277    ///     Ok(())
278    /// }
279    /// ```
280    #[stable(feature = "unix_socket", since = "1.10.0")]
281    pub fn try_clone(&self) -> io::Result<UnixDatagram> {
282        self.0.duplicate().map(UnixDatagram)
283    }
284
285    /// Returns the address of this socket.
286    ///
287    /// # Examples
288    ///
289    #[cfg_attr(target_family = "unix", doc = "```no_run")]
290    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
291    /// use std::os::unix::net::UnixDatagram;
292    ///
293    /// fn main() -> std::io::Result<()> {
294    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
295    ///     let addr = sock.local_addr().expect("Couldn't get local address");
296    ///     Ok(())
297    /// }
298    /// ```
299    #[stable(feature = "unix_socket", since = "1.10.0")]
300    pub fn local_addr(&self) -> io::Result<SocketAddr> {
301        SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.as_raw_fd(), addr, len) })
302    }
303
304    /// Returns the address of this socket's peer.
305    ///
306    /// The [`connect`] method will connect the socket to a peer.
307    ///
308    /// [`connect`]: UnixDatagram::connect
309    ///
310    /// # Examples
311    ///
312    #[cfg_attr(target_family = "unix", doc = "```no_run")]
313    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
314    /// use std::os::unix::net::UnixDatagram;
315    ///
316    /// fn main() -> std::io::Result<()> {
317    ///     let sock = UnixDatagram::unbound()?;
318    ///     sock.connect("/path/to/the/socket")?;
319    ///
320    ///     let addr = sock.peer_addr().expect("Couldn't get peer address");
321    ///     Ok(())
322    /// }
323    /// ```
324    #[stable(feature = "unix_socket", since = "1.10.0")]
325    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
326        SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.as_raw_fd(), addr, len) })
327    }
328
329    fn recv_from_flags(
330        &self,
331        buf: &mut [u8],
332        flags: core::ffi::c_int,
333    ) -> io::Result<(usize, SocketAddr)> {
334        let mut count = 0;
335        let addr = SocketAddr::new(|addr, len| unsafe {
336            count = libc::recvfrom(
337                self.as_raw_fd(),
338                buf.as_mut_ptr() as *mut _,
339                buf.len(),
340                flags,
341                addr,
342                len,
343            );
344            if count > 0 {
345                1
346            } else if count == 0 {
347                0
348            } else {
349                -1
350            }
351        })?;
352
353        Ok((count as usize, addr))
354    }
355
356    /// Receives data from the socket.
357    ///
358    /// On success, returns the number of bytes read and the address from
359    /// whence the data came.
360    ///
361    /// # Examples
362    ///
363    #[cfg_attr(target_family = "unix", doc = "```no_run")]
364    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
365    /// use std::os::unix::net::UnixDatagram;
366    ///
367    /// fn main() -> std::io::Result<()> {
368    ///     let sock = UnixDatagram::unbound()?;
369    ///     let mut buf = vec![0; 10];
370    ///     let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
371    ///     println!("received {size} bytes from {sender:?}");
372    ///     Ok(())
373    /// }
374    /// ```
375    #[stable(feature = "unix_socket", since = "1.10.0")]
376    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
377        self.recv_from_flags(buf, 0)
378    }
379
380    /// Receives data from the socket.
381    ///
382    /// On success, returns the number of bytes read.
383    ///
384    /// # Examples
385    ///
386    #[cfg_attr(target_family = "unix", doc = "```no_run")]
387    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
388    /// use std::os::unix::net::UnixDatagram;
389    ///
390    /// fn main() -> std::io::Result<()> {
391    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
392    ///     let mut buf = vec![0; 10];
393    ///     sock.recv(buf.as_mut_slice()).expect("recv function failed");
394    ///     Ok(())
395    /// }
396    /// ```
397    #[stable(feature = "unix_socket", since = "1.10.0")]
398    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
399        self.0.read(buf)
400    }
401
402    /// Receives data and ancillary data from socket.
403    ///
404    /// On success, returns the number of bytes read, if the data was truncated and the address from whence the msg came.
405    ///
406    /// # Examples
407    ///
408    #[cfg_attr(
409        any(target_os = "android", target_os = "linux", target_os = "cygwin"),
410        doc = "```no_run"
411    )]
412    #[cfg_attr(
413        not(any(target_os = "android", target_os = "linux", target_os = "cygwin")),
414        doc = "```ignore"
415    )]
416    /// #![feature(unix_socket_ancillary_data)]
417    /// use std::os::unix::net::{UnixDatagram, SocketAncillary, AncillaryData};
418    /// use std::io::IoSliceMut;
419    ///
420    /// fn main() -> std::io::Result<()> {
421    ///     let sock = UnixDatagram::unbound()?;
422    ///     let mut buf1 = [1; 8];
423    ///     let mut buf2 = [2; 16];
424    ///     let mut buf3 = [3; 8];
425    ///     let mut bufs = &mut [
426    ///         IoSliceMut::new(&mut buf1),
427    ///         IoSliceMut::new(&mut buf2),
428    ///         IoSliceMut::new(&mut buf3),
429    ///     ][..];
430    ///     let mut fds = [0; 8];
431    ///     let mut ancillary_buffer = [0; 128];
432    ///     let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
433    ///     let (size, _truncated, sender) = sock.recv_vectored_with_ancillary_from(bufs, &mut ancillary)?;
434    ///     println!("received {size}");
435    ///     for ancillary_result in ancillary.messages() {
436    ///         if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() {
437    ///             for fd in scm_rights {
438    ///                 println!("receive file descriptor: {fd}");
439    ///             }
440    ///         }
441    ///     }
442    ///     Ok(())
443    /// }
444    /// ```
445    #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
446    #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
447    pub fn recv_vectored_with_ancillary_from(
448        &self,
449        bufs: &mut [IoSliceMut<'_>],
450        ancillary: &mut SocketAncillary<'_>,
451    ) -> io::Result<(usize, bool, SocketAddr)> {
452        let (count, truncated, addr) = recv_vectored_with_ancillary_from(&self.0, bufs, ancillary)?;
453        let addr = addr?;
454
455        Ok((count, truncated, addr))
456    }
457
458    /// Receives data and ancillary data from socket.
459    ///
460    /// On success, returns the number of bytes read and if the data was truncated.
461    ///
462    /// # Examples
463    ///
464    #[cfg_attr(
465        any(target_os = "android", target_os = "linux", target_os = "cygwin"),
466        doc = "```no_run"
467    )]
468    #[cfg_attr(
469        not(any(target_os = "android", target_os = "linux", target_os = "cygwin")),
470        doc = "```ignore"
471    )]
472    /// #![feature(unix_socket_ancillary_data)]
473    /// use std::os::unix::net::{UnixDatagram, SocketAncillary, AncillaryData};
474    /// use std::io::IoSliceMut;
475    ///
476    /// fn main() -> std::io::Result<()> {
477    ///     let sock = UnixDatagram::unbound()?;
478    ///     let mut buf1 = [1; 8];
479    ///     let mut buf2 = [2; 16];
480    ///     let mut buf3 = [3; 8];
481    ///     let mut bufs = &mut [
482    ///         IoSliceMut::new(&mut buf1),
483    ///         IoSliceMut::new(&mut buf2),
484    ///         IoSliceMut::new(&mut buf3),
485    ///     ][..];
486    ///     let mut fds = [0; 8];
487    ///     let mut ancillary_buffer = [0; 128];
488    ///     let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
489    ///     let (size, _truncated) = sock.recv_vectored_with_ancillary(bufs, &mut ancillary)?;
490    ///     println!("received {size}");
491    ///     for ancillary_result in ancillary.messages() {
492    ///         if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() {
493    ///             for fd in scm_rights {
494    ///                 println!("receive file descriptor: {fd}");
495    ///             }
496    ///         }
497    ///     }
498    ///     Ok(())
499    /// }
500    /// ```
501    #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
502    #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
503    pub fn recv_vectored_with_ancillary(
504        &self,
505        bufs: &mut [IoSliceMut<'_>],
506        ancillary: &mut SocketAncillary<'_>,
507    ) -> io::Result<(usize, bool)> {
508        let (count, truncated, addr) = recv_vectored_with_ancillary_from(&self.0, bufs, ancillary)?;
509        addr?;
510
511        Ok((count, truncated))
512    }
513
514    /// Sends data on the socket to the specified address.
515    ///
516    /// On success, returns the number of bytes written.
517    ///
518    /// # Examples
519    ///
520    #[cfg_attr(target_family = "unix", doc = "```no_run")]
521    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
522    /// use std::os::unix::net::UnixDatagram;
523    ///
524    /// fn main() -> std::io::Result<()> {
525    ///     let sock = UnixDatagram::unbound()?;
526    ///     sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
527    ///     Ok(())
528    /// }
529    /// ```
530    #[stable(feature = "unix_socket", since = "1.10.0")]
531    pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
532        unsafe {
533            let (addr, len) = sockaddr_un(path.as_ref())?;
534
535            let count = cvt(libc::sendto(
536                self.as_raw_fd(),
537                buf.as_ptr() as *const _,
538                buf.len(),
539                MSG_NOSIGNAL,
540                (&raw const addr) as *const _,
541                len,
542            ))?;
543            Ok(count as usize)
544        }
545    }
546
547    /// Sends data on the socket to the specified [SocketAddr].
548    ///
549    /// On success, returns the number of bytes written.
550    ///
551    /// [SocketAddr]: crate::os::unix::net::SocketAddr
552    ///
553    /// # Examples
554    ///
555    #[cfg_attr(target_family = "unix", doc = "```no_run")]
556    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
557    /// use std::os::unix::net::{UnixDatagram};
558    ///
559    /// fn main() -> std::io::Result<()> {
560    ///     let bound = UnixDatagram::bind("/path/to/socket")?;
561    ///     let addr = bound.local_addr()?;
562    ///
563    ///     let sock = UnixDatagram::unbound()?;
564    ///     sock.send_to_addr(b"bacon egg and cheese", &addr).expect("send_to_addr function failed");
565    ///     Ok(())
566    /// }
567    /// ```
568    #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
569    pub fn send_to_addr(&self, buf: &[u8], socket_addr: &SocketAddr) -> io::Result<usize> {
570        unsafe {
571            let count = cvt(libc::sendto(
572                self.as_raw_fd(),
573                buf.as_ptr() as *const _,
574                buf.len(),
575                MSG_NOSIGNAL,
576                (&raw const socket_addr.addr) as *const _,
577                socket_addr.len,
578            ))?;
579            Ok(count as usize)
580        }
581    }
582
583    /// Sends data on the socket to the socket's peer.
584    ///
585    /// The peer address may be set by the `connect` method, and this method
586    /// will return an error if the socket has not already been connected.
587    ///
588    /// On success, returns the number of bytes written.
589    ///
590    /// # Examples
591    ///
592    #[cfg_attr(target_family = "unix", doc = "```no_run")]
593    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
594    /// use std::os::unix::net::UnixDatagram;
595    ///
596    /// fn main() -> std::io::Result<()> {
597    ///     let sock = UnixDatagram::unbound()?;
598    ///     sock.connect("/some/sock").expect("Couldn't connect");
599    ///     sock.send(b"omelette au fromage").expect("send_to function failed");
600    ///     Ok(())
601    /// }
602    /// ```
603    #[stable(feature = "unix_socket", since = "1.10.0")]
604    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
605        self.0.write(buf)
606    }
607
608    /// Sends data and ancillary data on the socket to the specified address.
609    ///
610    /// On success, returns the number of bytes written.
611    ///
612    /// # Examples
613    ///
614    #[cfg_attr(
615        any(target_os = "android", target_os = "linux", target_os = "cygwin"),
616        doc = "```no_run"
617    )]
618    #[cfg_attr(
619        not(any(target_os = "android", target_os = "linux", target_os = "cygwin")),
620        doc = "```ignore"
621    )]
622    /// #![feature(unix_socket_ancillary_data)]
623    /// use std::os::unix::net::{UnixDatagram, SocketAncillary};
624    /// use std::io::IoSlice;
625    ///
626    /// fn main() -> std::io::Result<()> {
627    ///     let sock = UnixDatagram::unbound()?;
628    ///     let buf1 = [1; 8];
629    ///     let buf2 = [2; 16];
630    ///     let buf3 = [3; 8];
631    ///     let bufs = &[
632    ///         IoSlice::new(&buf1),
633    ///         IoSlice::new(&buf2),
634    ///         IoSlice::new(&buf3),
635    ///     ][..];
636    ///     let fds = [0, 1, 2];
637    ///     let mut ancillary_buffer = [0; 128];
638    ///     let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
639    ///     ancillary.add_fds(&fds[..]);
640    ///     sock.send_vectored_with_ancillary_to(bufs, &mut ancillary, "/some/sock")
641    ///         .expect("send_vectored_with_ancillary_to function failed");
642    ///     Ok(())
643    /// }
644    /// ```
645    #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
646    #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
647    pub fn send_vectored_with_ancillary_to<P: AsRef<Path>>(
648        &self,
649        bufs: &[IoSlice<'_>],
650        ancillary: &mut SocketAncillary<'_>,
651        path: P,
652    ) -> io::Result<usize> {
653        send_vectored_with_ancillary_to(&self.0, Some(path.as_ref()), bufs, ancillary)
654    }
655
656    /// Sends data and ancillary data on the socket.
657    ///
658    /// On success, returns the number of bytes written.
659    ///
660    /// # Examples
661    ///
662    #[cfg_attr(
663        any(target_os = "android", target_os = "linux", target_os = "cygwin"),
664        doc = "```no_run"
665    )]
666    #[cfg_attr(
667        not(any(target_os = "android", target_os = "linux", target_os = "cygwin")),
668        doc = "```ignore"
669    )]
670    /// #![feature(unix_socket_ancillary_data)]
671    /// use std::os::unix::net::{UnixDatagram, SocketAncillary};
672    /// use std::io::IoSlice;
673    ///
674    /// fn main() -> std::io::Result<()> {
675    ///     let sock = UnixDatagram::unbound()?;
676    ///     let buf1 = [1; 8];
677    ///     let buf2 = [2; 16];
678    ///     let buf3 = [3; 8];
679    ///     let bufs = &[
680    ///         IoSlice::new(&buf1),
681    ///         IoSlice::new(&buf2),
682    ///         IoSlice::new(&buf3),
683    ///     ][..];
684    ///     let fds = [0, 1, 2];
685    ///     let mut ancillary_buffer = [0; 128];
686    ///     let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
687    ///     ancillary.add_fds(&fds[..]);
688    ///     sock.send_vectored_with_ancillary(bufs, &mut ancillary)
689    ///         .expect("send_vectored_with_ancillary function failed");
690    ///     Ok(())
691    /// }
692    /// ```
693    #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
694    #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
695    pub fn send_vectored_with_ancillary(
696        &self,
697        bufs: &[IoSlice<'_>],
698        ancillary: &mut SocketAncillary<'_>,
699    ) -> io::Result<usize> {
700        send_vectored_with_ancillary_to(&self.0, None, bufs, ancillary)
701    }
702
703    /// Sets the read timeout for the socket.
704    ///
705    /// If the provided value is [`None`], then [`recv`] and [`recv_from`] calls will
706    /// block indefinitely. An [`Err`] is returned if the zero [`Duration`]
707    /// is passed to this method.
708    ///
709    /// [`recv`]: UnixDatagram::recv
710    /// [`recv_from`]: UnixDatagram::recv_from
711    ///
712    /// # Examples
713    ///
714    #[cfg_attr(target_family = "unix", doc = "```")]
715    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
716    /// use std::os::unix::net::UnixDatagram;
717    /// use std::time::Duration;
718    ///
719    /// fn main() -> std::io::Result<()> {
720    ///     let sock = UnixDatagram::unbound()?;
721    ///     sock.set_read_timeout(Some(Duration::new(1, 0)))
722    ///         .expect("set_read_timeout function failed");
723    ///     Ok(())
724    /// }
725    /// ```
726    ///
727    /// An [`Err`] is returned if the zero [`Duration`] is passed to this
728    /// method:
729    ///
730    #[cfg_attr(target_family = "unix", doc = "```no_run")]
731    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
732    /// use std::io;
733    /// use std::os::unix::net::UnixDatagram;
734    /// use std::time::Duration;
735    ///
736    /// fn main() -> std::io::Result<()> {
737    ///     let socket = UnixDatagram::unbound()?;
738    ///     let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
739    ///     let err = result.unwrap_err();
740    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
741    ///     Ok(())
742    /// }
743    /// ```
744    #[stable(feature = "unix_socket", since = "1.10.0")]
745    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
746        self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
747    }
748
749    /// Sets the write timeout for the socket.
750    ///
751    /// If the provided value is [`None`], then [`send`] and [`send_to`] calls will
752    /// block indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
753    /// method.
754    ///
755    /// [`send`]: UnixDatagram::send
756    /// [`send_to`]: UnixDatagram::send_to
757    ///
758    /// # Examples
759    ///
760    #[cfg_attr(target_family = "unix", doc = "```")]
761    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
762    /// use std::os::unix::net::UnixDatagram;
763    /// use std::time::Duration;
764    ///
765    /// fn main() -> std::io::Result<()> {
766    ///     let sock = UnixDatagram::unbound()?;
767    ///     sock.set_write_timeout(Some(Duration::new(1, 0)))
768    ///         .expect("set_write_timeout function failed");
769    ///     Ok(())
770    /// }
771    /// ```
772    ///
773    /// An [`Err`] is returned if the zero [`Duration`] is passed to this
774    /// method:
775    ///
776    #[cfg_attr(target_family = "unix", doc = "```no_run")]
777    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
778    /// use std::io;
779    /// use std::os::unix::net::UnixDatagram;
780    /// use std::time::Duration;
781    ///
782    /// fn main() -> std::io::Result<()> {
783    ///     let socket = UnixDatagram::unbound()?;
784    ///     let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
785    ///     let err = result.unwrap_err();
786    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
787    ///     Ok(())
788    /// }
789    /// ```
790    #[stable(feature = "unix_socket", since = "1.10.0")]
791    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
792        self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
793    }
794
795    /// Returns the read timeout of this socket.
796    ///
797    /// # Examples
798    ///
799    #[cfg_attr(target_family = "unix", doc = "```")]
800    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
801    /// use std::os::unix::net::UnixDatagram;
802    /// use std::time::Duration;
803    ///
804    /// fn main() -> std::io::Result<()> {
805    ///     let sock = UnixDatagram::unbound()?;
806    ///     sock.set_read_timeout(Some(Duration::new(1, 0)))
807    ///         .expect("set_read_timeout function failed");
808    ///     assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
809    ///     Ok(())
810    /// }
811    /// ```
812    #[stable(feature = "unix_socket", since = "1.10.0")]
813    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
814        self.0.timeout(libc::SO_RCVTIMEO)
815    }
816
817    /// Returns the write timeout of this socket.
818    ///
819    /// # Examples
820    ///
821    #[cfg_attr(target_family = "unix", doc = "```")]
822    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
823    /// use std::os::unix::net::UnixDatagram;
824    /// use std::time::Duration;
825    ///
826    /// fn main() -> std::io::Result<()> {
827    ///     let sock = UnixDatagram::unbound()?;
828    ///     sock.set_write_timeout(Some(Duration::new(1, 0)))
829    ///         .expect("set_write_timeout function failed");
830    ///     assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
831    ///     Ok(())
832    /// }
833    /// ```
834    #[stable(feature = "unix_socket", since = "1.10.0")]
835    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
836        self.0.timeout(libc::SO_SNDTIMEO)
837    }
838
839    /// Moves the socket into or out of nonblocking mode.
840    ///
841    /// # Examples
842    ///
843    #[cfg_attr(target_family = "unix", doc = "```")]
844    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
845    /// use std::os::unix::net::UnixDatagram;
846    ///
847    /// fn main() -> std::io::Result<()> {
848    ///     let sock = UnixDatagram::unbound()?;
849    ///     sock.set_nonblocking(true).expect("set_nonblocking function failed");
850    ///     Ok(())
851    /// }
852    /// ```
853    #[stable(feature = "unix_socket", since = "1.10.0")]
854    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
855        self.0.set_nonblocking(nonblocking)
856    }
857
858    /// Set the id of the socket for network filtering purpose
859    ///
860    #[cfg_attr(
861        any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"),
862        doc = "```no_run"
863    )]
864    #[cfg_attr(
865        not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")),
866        doc = "```ignore"
867    )]
868    /// #![feature(unix_set_mark)]
869    /// use std::os::unix::net::UnixDatagram;
870    ///
871    /// fn main() -> std::io::Result<()> {
872    ///     let sock = UnixDatagram::unbound()?;
873    ///     sock.set_mark(32)?;
874    ///     Ok(())
875    /// }
876    /// ```
877    #[cfg(any(doc, target_os = "linux", target_os = "freebsd", target_os = "openbsd",))]
878    #[unstable(feature = "unix_set_mark", issue = "96467")]
879    pub fn set_mark(&self, mark: u32) -> io::Result<()> {
880        self.0.set_mark(mark)
881    }
882
883    /// Returns the value of the `SO_ERROR` option.
884    ///
885    /// # Examples
886    ///
887    #[cfg_attr(target_family = "unix", doc = "```no_run")]
888    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
889    /// use std::os::unix::net::UnixDatagram;
890    ///
891    /// fn main() -> std::io::Result<()> {
892    ///     let sock = UnixDatagram::unbound()?;
893    ///     if let Ok(Some(err)) = sock.take_error() {
894    ///         println!("Got error: {err:?}");
895    ///     }
896    ///     Ok(())
897    /// }
898    /// ```
899    #[stable(feature = "unix_socket", since = "1.10.0")]
900    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
901        self.0.take_error()
902    }
903
904    /// Shut down the read, write, or both halves of this connection.
905    ///
906    /// This function will cause all pending and future I/O calls on the
907    /// specified portions to immediately return with an appropriate value
908    /// (see the documentation of [`Shutdown`]).
909    ///
910    #[cfg_attr(target_family = "unix", doc = "```no_run")]
911    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
912    /// use std::os::unix::net::UnixDatagram;
913    /// use std::net::Shutdown;
914    ///
915    /// fn main() -> std::io::Result<()> {
916    ///     let sock = UnixDatagram::unbound()?;
917    ///     sock.shutdown(Shutdown::Both).expect("shutdown function failed");
918    ///     Ok(())
919    /// }
920    /// ```
921    #[stable(feature = "unix_socket", since = "1.10.0")]
922    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
923        self.0.shutdown(how)
924    }
925
926    /// Receives data on the socket from the remote address to which it is
927    /// connected, without removing that data from the queue. On success,
928    /// returns the number of bytes peeked.
929    ///
930    /// Successive calls return the same data. This is accomplished by passing
931    /// `MSG_PEEK` as a flag to the underlying `recv` system call.
932    ///
933    /// # Examples
934    ///
935    #[cfg_attr(target_family = "unix", doc = "```no_run")]
936    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
937    /// #![feature(unix_socket_peek)]
938    ///
939    /// use std::os::unix::net::UnixDatagram;
940    ///
941    /// fn main() -> std::io::Result<()> {
942    ///     let socket = UnixDatagram::bind("/tmp/sock")?;
943    ///     let mut buf = [0; 10];
944    ///     let len = socket.peek(&mut buf).expect("peek failed");
945    ///     Ok(())
946    /// }
947    /// ```
948    #[unstable(feature = "unix_socket_peek", issue = "76923")]
949    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
950        self.0.peek(buf)
951    }
952
953    /// Receives a single datagram message on the socket, without removing it from the
954    /// queue. On success, returns the number of bytes read and the origin.
955    ///
956    /// The function must be called with valid byte array `buf` of sufficient size to
957    /// hold the message bytes. If a message is too long to fit in the supplied buffer,
958    /// excess bytes may be discarded.
959    ///
960    /// Successive calls return the same data. This is accomplished by passing
961    /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
962    ///
963    /// Do not use this function to implement busy waiting, instead use `libc::poll` to
964    /// synchronize IO events on one or more sockets.
965    ///
966    /// # Examples
967    ///
968    #[cfg_attr(target_family = "unix", doc = "```no_run")]
969    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
970    /// #![feature(unix_socket_peek)]
971    ///
972    /// use std::os::unix::net::UnixDatagram;
973    ///
974    /// fn main() -> std::io::Result<()> {
975    ///     let socket = UnixDatagram::bind("/tmp/sock")?;
976    ///     let mut buf = [0; 10];
977    ///     let (len, addr) = socket.peek_from(&mut buf).expect("peek failed");
978    ///     Ok(())
979    /// }
980    /// ```
981    #[unstable(feature = "unix_socket_peek", issue = "76923")]
982    pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
983        self.recv_from_flags(buf, libc::MSG_PEEK)
984    }
985}
986
987#[stable(feature = "unix_socket", since = "1.10.0")]
988impl AsRawFd for UnixDatagram {
989    #[inline]
990    fn as_raw_fd(&self) -> RawFd {
991        self.0.as_inner().as_raw_fd()
992    }
993}
994
995#[stable(feature = "unix_socket", since = "1.10.0")]
996impl FromRawFd for UnixDatagram {
997    #[inline]
998    unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
999        UnixDatagram(Socket::from_inner(FromInner::from_inner(OwnedFd::from_raw_fd(fd))))
1000    }
1001}
1002
1003#[stable(feature = "unix_socket", since = "1.10.0")]
1004impl IntoRawFd for UnixDatagram {
1005    #[inline]
1006    fn into_raw_fd(self) -> RawFd {
1007        self.0.into_inner().into_inner().into_raw_fd()
1008    }
1009}
1010
1011#[stable(feature = "io_safety", since = "1.63.0")]
1012impl AsFd for UnixDatagram {
1013    #[inline]
1014    fn as_fd(&self) -> BorrowedFd<'_> {
1015        self.0.as_inner().as_fd()
1016    }
1017}
1018
1019#[stable(feature = "io_safety", since = "1.63.0")]
1020impl From<UnixDatagram> for OwnedFd {
1021    /// Takes ownership of a [`UnixDatagram`]'s socket file descriptor.
1022    #[inline]
1023    fn from(unix_datagram: UnixDatagram) -> OwnedFd {
1024        unsafe { OwnedFd::from_raw_fd(unix_datagram.into_raw_fd()) }
1025    }
1026}
1027
1028#[stable(feature = "io_safety", since = "1.63.0")]
1029impl From<OwnedFd> for UnixDatagram {
1030    #[inline]
1031    fn from(owned: OwnedFd) -> Self {
1032        unsafe { Self::from_raw_fd(owned.into_raw_fd()) }
1033    }
1034}
1035
1036impl AsInner<Socket> for UnixDatagram {
1037    #[inline]
1038    fn as_inner(&self) -> &Socket {
1039        &self.0
1040    }
1041}