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