std/os/net/linux_ext/addr.rs
1//! Linux and Android-specific extensions to socket addresses.
2
3use crate::os::unix::net::SocketAddr;
4use crate::sealed::Sealed;
5
6/// Platform-specific extensions to [`SocketAddr`].
7#[stable(feature = "unix_socket_abstract", since = "1.70.0")]
8pub trait SocketAddrExt: Sealed {
9 /// Creates a Unix socket address in the abstract namespace.
10 ///
11 /// The abstract namespace is a Linux-specific extension that allows Unix
12 /// sockets to be bound without creating an entry in the filesystem.
13 /// Abstract sockets are unaffected by filesystem layout or permissions,
14 /// and no cleanup is necessary when the socket is closed.
15 ///
16 /// An abstract socket address name may contain any bytes, including zero.
17 ///
18 /// # Errors
19 ///
20 /// Returns an error if the name is longer than `SUN_LEN - 1`.
21 ///
22 /// # Examples
23 ///
24 /// ```no_run
25 /// use std::os::unix::net::{UnixListener, SocketAddr};
26 /// #[cfg(target_os = "linux")]
27 /// use std::os::linux::net::SocketAddrExt;
28 /// #[cfg(target_os = "android")]
29 /// use std::os::android::net::SocketAddrExt;
30 ///
31 /// fn main() -> std::io::Result<()> {
32 /// let addr = SocketAddr::from_abstract_name(b"hidden")?;
33 /// let listener = match UnixListener::bind_addr(&addr) {
34 /// Ok(sock) => sock,
35 /// Err(err) => {
36 /// println!("Couldn't bind: {err:?}");
37 /// return Err(err);
38 /// }
39 /// };
40 /// Ok(())
41 /// }
42 /// ```
43 #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
44 fn from_abstract_name<N>(name: N) -> crate::io::Result<SocketAddr>
45 where
46 N: AsRef<[u8]>;
47
48 /// Returns the contents of this address if it is in the abstract namespace.
49 ///
50 /// # Examples
51 ///
52 /// ```no_run
53 /// use std::os::unix::net::{UnixListener, SocketAddr};
54 /// #[cfg(target_os = "linux")]
55 /// use std::os::linux::net::SocketAddrExt;
56 /// #[cfg(target_os = "android")]
57 /// use std::os::android::net::SocketAddrExt;
58 ///
59 /// fn main() -> std::io::Result<()> {
60 /// let name = b"hidden";
61 /// let name_addr = SocketAddr::from_abstract_name(name)?;
62 /// let socket = UnixListener::bind_addr(&name_addr)?;
63 /// let local_addr = socket.local_addr().expect("Couldn't get local address");
64 /// assert_eq!(local_addr.as_abstract_name(), Some(&name[..]));
65 /// Ok(())
66 /// }
67 /// ```
68 #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
69 fn as_abstract_name(&self) -> Option<&[u8]>;
70}