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