1 #[cfg(any(doc, target_os = "android", target_os = "linux"))]
2 use super::{recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to, SocketAncillary};
3 use super::{sockaddr_un, SocketAddr};
5 use crate::io::{self, IoSlice, IoSliceMut};
6 use crate::net::Shutdown;
7 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
11 target_os = "dragonfly",
12 target_os = "freebsd",
15 target_os = "watchos",
19 use crate::os::unix::ucred;
20 use crate::path::Path;
22 use crate::sys::net::Socket;
23 use crate::sys_common::{AsInner, FromInner};
24 use crate::time::Duration;
26 #[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")]
28 target_os = "android",
30 target_os = "dragonfly",
31 target_os = "freebsd",
34 target_os = "watchos",
40 /// A Unix stream socket.
45 /// use std::os::unix::net::UnixStream;
46 /// use std::io::prelude::*;
48 /// fn main() -> std::io::Result<()> {
49 /// let mut stream = UnixStream::connect("/path/to/my/socket")?;
50 /// stream.write_all(b"hello world")?;
51 /// let mut response = String::new();
52 /// stream.read_to_string(&mut response)?;
53 /// println!("{response}");
57 #[stable(feature = "unix_socket", since = "1.10.0")]
58 pub struct UnixStream(pub(super) Socket);
60 #[stable(feature = "unix_socket", since = "1.10.0")]
61 impl fmt::Debug for UnixStream {
62 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
63 let mut builder = fmt.debug_struct("UnixStream");
64 builder.field("fd", self.0.as_inner());
65 if let Ok(addr) = self.local_addr() {
66 builder.field("local", &addr);
68 if let Ok(addr) = self.peer_addr() {
69 builder.field("peer", &addr);
76 /// Connects to the socket named by `path`.
81 /// use std::os::unix::net::UnixStream;
83 /// let socket = match UnixStream::connect("/tmp/sock") {
86 /// println!("Couldn't connect: {e:?}");
91 #[stable(feature = "unix_socket", since = "1.10.0")]
92 pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
94 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
95 let (addr, len) = sockaddr_un(path.as_ref())?;
97 cvt(libc::connect(inner.as_raw_fd(), &addr as *const _ as *const _, len))?;
102 /// Connects to the socket specified by [`address`].
104 /// [`address`]: crate::os::unix::net::SocketAddr
109 /// #![feature(unix_socket_abstract)]
110 /// use std::os::unix::net::{UnixListener, UnixStream};
112 /// fn main() -> std::io::Result<()> {
113 /// let listener = UnixListener::bind("/path/to/the/socket")?;
114 /// let addr = listener.local_addr()?;
116 /// let sock = match UnixStream::connect_addr(&addr) {
117 /// Ok(sock) => sock,
119 /// println!("Couldn't connect: {e:?}");
126 #[unstable(feature = "unix_socket_abstract", issue = "85410")]
127 pub fn connect_addr(socket_addr: &SocketAddr) -> io::Result<UnixStream> {
129 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
132 &socket_addr.addr as *const _ as *const _,
135 Ok(UnixStream(inner))
139 /// Creates an unnamed pair of connected sockets.
141 /// Returns two `UnixStream`s which are connected to each other.
146 /// use std::os::unix::net::UnixStream;
148 /// let (sock1, sock2) = match UnixStream::pair() {
149 /// Ok((sock1, sock2)) => (sock1, sock2),
151 /// println!("Couldn't create a pair of sockets: {e:?}");
156 #[stable(feature = "unix_socket", since = "1.10.0")]
157 pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
158 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM)?;
159 Ok((UnixStream(i1), UnixStream(i2)))
162 /// Creates a new independently owned handle to the underlying socket.
164 /// The returned `UnixStream` is a reference to the same stream that this
165 /// object references. Both handles will read and write the same stream of
166 /// data, and options set on one stream will be propagated to the other
172 /// use std::os::unix::net::UnixStream;
174 /// fn main() -> std::io::Result<()> {
175 /// let socket = UnixStream::connect("/tmp/sock")?;
176 /// let sock_copy = socket.try_clone().expect("Couldn't clone socket");
180 #[stable(feature = "unix_socket", since = "1.10.0")]
181 pub fn try_clone(&self) -> io::Result<UnixStream> {
182 self.0.duplicate().map(UnixStream)
185 /// Returns the socket address of the local half of this connection.
190 /// use std::os::unix::net::UnixStream;
192 /// fn main() -> std::io::Result<()> {
193 /// let socket = UnixStream::connect("/tmp/sock")?;
194 /// let addr = socket.local_addr().expect("Couldn't get local address");
198 #[stable(feature = "unix_socket", since = "1.10.0")]
199 pub fn local_addr(&self) -> io::Result<SocketAddr> {
200 SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.as_raw_fd(), addr, len) })
203 /// Returns the socket address of the remote half of this connection.
208 /// use std::os::unix::net::UnixStream;
210 /// fn main() -> std::io::Result<()> {
211 /// let socket = UnixStream::connect("/tmp/sock")?;
212 /// let addr = socket.peer_addr().expect("Couldn't get peer address");
216 #[stable(feature = "unix_socket", since = "1.10.0")]
217 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
218 SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.as_raw_fd(), addr, len) })
221 /// Gets the peer credentials for this Unix domain socket.
226 /// #![feature(peer_credentials_unix_socket)]
227 /// use std::os::unix::net::UnixStream;
229 /// fn main() -> std::io::Result<()> {
230 /// let socket = UnixStream::connect("/tmp/sock")?;
231 /// let peer_cred = socket.peer_cred().expect("Couldn't get peer credentials");
235 #[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")]
237 target_os = "android",
239 target_os = "dragonfly",
240 target_os = "freebsd",
243 target_os = "watchos",
244 target_os = "netbsd",
245 target_os = "openbsd"
247 pub fn peer_cred(&self) -> io::Result<UCred> {
248 ucred::peer_cred(self)
251 /// Sets the read timeout for the socket.
253 /// If the provided value is [`None`], then [`read`] calls will block
254 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
257 /// [`read`]: io::Read::read
262 /// use std::os::unix::net::UnixStream;
263 /// use std::time::Duration;
265 /// fn main() -> std::io::Result<()> {
266 /// let socket = UnixStream::connect("/tmp/sock")?;
267 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
272 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
277 /// use std::os::unix::net::UnixStream;
278 /// use std::time::Duration;
280 /// fn main() -> std::io::Result<()> {
281 /// let socket = UnixStream::connect("/tmp/sock")?;
282 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
283 /// let err = result.unwrap_err();
284 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
288 #[stable(feature = "unix_socket", since = "1.10.0")]
289 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
290 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
293 /// Sets the write timeout for the socket.
295 /// If the provided value is [`None`], then [`write`] calls will block
296 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
297 /// passed to this method.
299 /// [`read`]: io::Read::read
304 /// use std::os::unix::net::UnixStream;
305 /// use std::time::Duration;
307 /// fn main() -> std::io::Result<()> {
308 /// let socket = UnixStream::connect("/tmp/sock")?;
309 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
310 /// .expect("Couldn't set write timeout");
315 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
320 /// use std::net::UdpSocket;
321 /// use std::time::Duration;
323 /// fn main() -> std::io::Result<()> {
324 /// let socket = UdpSocket::bind("127.0.0.1:34254")?;
325 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
326 /// let err = result.unwrap_err();
327 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
331 #[stable(feature = "unix_socket", since = "1.10.0")]
332 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
333 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
336 /// Returns the read timeout of this socket.
341 /// use std::os::unix::net::UnixStream;
342 /// use std::time::Duration;
344 /// fn main() -> std::io::Result<()> {
345 /// let socket = UnixStream::connect("/tmp/sock")?;
346 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
347 /// assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
351 #[stable(feature = "unix_socket", since = "1.10.0")]
352 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
353 self.0.timeout(libc::SO_RCVTIMEO)
356 /// Returns the write timeout of this socket.
361 /// use std::os::unix::net::UnixStream;
362 /// use std::time::Duration;
364 /// fn main() -> std::io::Result<()> {
365 /// let socket = UnixStream::connect("/tmp/sock")?;
366 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
367 /// .expect("Couldn't set write timeout");
368 /// assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
372 #[stable(feature = "unix_socket", since = "1.10.0")]
373 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
374 self.0.timeout(libc::SO_SNDTIMEO)
377 /// Moves the socket into or out of nonblocking mode.
382 /// use std::os::unix::net::UnixStream;
384 /// fn main() -> std::io::Result<()> {
385 /// let socket = UnixStream::connect("/tmp/sock")?;
386 /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
390 #[stable(feature = "unix_socket", since = "1.10.0")]
391 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
392 self.0.set_nonblocking(nonblocking)
395 /// Moves the socket to pass unix credentials as control message in [`SocketAncillary`].
397 /// Set the socket option `SO_PASSCRED`.
401 #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")]
402 #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")]
403 /// #![feature(unix_socket_ancillary_data)]
404 /// use std::os::unix::net::UnixStream;
406 /// fn main() -> std::io::Result<()> {
407 /// let socket = UnixStream::connect("/tmp/sock")?;
408 /// socket.set_passcred(true).expect("Couldn't set passcred");
412 #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "netbsd",))]
413 #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
414 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
415 self.0.set_passcred(passcred)
418 /// Get the current value of the socket for passing unix credentials in [`SocketAncillary`].
419 /// This value can be change by [`set_passcred`].
421 /// Get the socket option `SO_PASSCRED`.
423 /// [`set_passcred`]: UnixStream::set_passcred
424 #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "netbsd",))]
425 #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
426 pub fn passcred(&self) -> io::Result<bool> {
430 /// Set the id of the socket for network filtering purpose
433 any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"),
437 not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")),
440 /// #![feature(unix_set_mark)]
441 /// use std::os::unix::net::UnixStream;
443 /// fn main() -> std::io::Result<()> {
444 /// let sock = UnixStream::connect("/tmp/sock")?;
445 /// sock.set_mark(32)?;
449 #[cfg(any(doc, target_os = "linux", target_os = "freebsd", target_os = "openbsd",))]
450 #[unstable(feature = "unix_set_mark", issue = "96467")]
451 pub fn set_mark(&self, mark: u32) -> io::Result<()> {
452 self.0.set_mark(mark)
455 /// Returns the value of the `SO_ERROR` option.
460 /// use std::os::unix::net::UnixStream;
462 /// fn main() -> std::io::Result<()> {
463 /// let socket = UnixStream::connect("/tmp/sock")?;
464 /// if let Ok(Some(err)) = socket.take_error() {
465 /// println!("Got error: {err:?}");
471 /// # Platform specific
472 /// On Redox this always returns `None`.
473 #[stable(feature = "unix_socket", since = "1.10.0")]
474 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
478 /// Shuts down the read, write, or both halves of this connection.
480 /// This function will cause all pending and future I/O calls on the
481 /// specified portions to immediately return with an appropriate value
482 /// (see the documentation of [`Shutdown`]).
487 /// use std::os::unix::net::UnixStream;
488 /// use std::net::Shutdown;
490 /// fn main() -> std::io::Result<()> {
491 /// let socket = UnixStream::connect("/tmp/sock")?;
492 /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
496 #[stable(feature = "unix_socket", since = "1.10.0")]
497 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
501 /// Receives data on the socket from the remote address to which it is
502 /// connected, without removing that data from the queue. On success,
503 /// returns the number of bytes peeked.
505 /// Successive calls return the same data. This is accomplished by passing
506 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
511 /// #![feature(unix_socket_peek)]
513 /// use std::os::unix::net::UnixStream;
515 /// fn main() -> std::io::Result<()> {
516 /// let socket = UnixStream::connect("/tmp/sock")?;
517 /// let mut buf = [0; 10];
518 /// let len = socket.peek(&mut buf).expect("peek failed");
522 #[unstable(feature = "unix_socket_peek", issue = "76923")]
523 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
527 /// Receives data and ancillary data from socket.
529 /// On success, returns the number of bytes read.
533 #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")]
534 #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")]
535 /// #![feature(unix_socket_ancillary_data)]
536 /// use std::os::unix::net::{UnixStream, SocketAncillary, AncillaryData};
537 /// use std::io::IoSliceMut;
539 /// fn main() -> std::io::Result<()> {
540 /// let socket = UnixStream::connect("/tmp/sock")?;
541 /// let mut buf1 = [1; 8];
542 /// let mut buf2 = [2; 16];
543 /// let mut buf3 = [3; 8];
544 /// let mut bufs = &mut [
545 /// IoSliceMut::new(&mut buf1),
546 /// IoSliceMut::new(&mut buf2),
547 /// IoSliceMut::new(&mut buf3),
549 /// let mut fds = [0; 8];
550 /// let mut ancillary_buffer = [0; 128];
551 /// let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
552 /// let size = socket.recv_vectored_with_ancillary(bufs, &mut ancillary)?;
553 /// println!("received {size}");
554 /// for ancillary_result in ancillary.messages() {
555 /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() {
556 /// for fd in scm_rights {
557 /// println!("receive file descriptor: {fd}");
564 #[cfg(any(doc, target_os = "android", target_os = "linux"))]
565 #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
566 pub fn recv_vectored_with_ancillary(
568 bufs: &mut [IoSliceMut<'_>],
569 ancillary: &mut SocketAncillary<'_>,
570 ) -> io::Result<usize> {
571 let (count, _, _) = recv_vectored_with_ancillary_from(&self.0, bufs, ancillary)?;
576 /// Sends data and ancillary data on the socket.
578 /// On success, returns the number of bytes written.
582 #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")]
583 #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")]
584 /// #![feature(unix_socket_ancillary_data)]
585 /// use std::os::unix::net::{UnixStream, SocketAncillary};
586 /// use std::io::IoSlice;
588 /// fn main() -> std::io::Result<()> {
589 /// let socket = UnixStream::connect("/tmp/sock")?;
590 /// let buf1 = [1; 8];
591 /// let buf2 = [2; 16];
592 /// let buf3 = [3; 8];
594 /// IoSlice::new(&buf1),
595 /// IoSlice::new(&buf2),
596 /// IoSlice::new(&buf3),
598 /// let fds = [0, 1, 2];
599 /// let mut ancillary_buffer = [0; 128];
600 /// let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
601 /// ancillary.add_fds(&fds[..]);
602 /// socket.send_vectored_with_ancillary(bufs, &mut ancillary)
603 /// .expect("send_vectored_with_ancillary function failed");
607 #[cfg(any(doc, target_os = "android", target_os = "linux"))]
608 #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
609 pub fn send_vectored_with_ancillary(
611 bufs: &[IoSlice<'_>],
612 ancillary: &mut SocketAncillary<'_>,
613 ) -> io::Result<usize> {
614 send_vectored_with_ancillary_to(&self.0, None, bufs, ancillary)
618 #[stable(feature = "unix_socket", since = "1.10.0")]
619 impl io::Read for UnixStream {
620 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
621 io::Read::read(&mut &*self, buf)
624 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
625 io::Read::read_vectored(&mut &*self, bufs)
629 fn is_read_vectored(&self) -> bool {
630 io::Read::is_read_vectored(&&*self)
634 #[stable(feature = "unix_socket", since = "1.10.0")]
635 impl<'a> io::Read for &'a UnixStream {
636 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
640 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
641 self.0.read_vectored(bufs)
645 fn is_read_vectored(&self) -> bool {
646 self.0.is_read_vectored()
650 #[stable(feature = "unix_socket", since = "1.10.0")]
651 impl io::Write for UnixStream {
652 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
653 io::Write::write(&mut &*self, buf)
656 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
657 io::Write::write_vectored(&mut &*self, bufs)
661 fn is_write_vectored(&self) -> bool {
662 io::Write::is_write_vectored(&&*self)
665 fn flush(&mut self) -> io::Result<()> {
666 io::Write::flush(&mut &*self)
670 #[stable(feature = "unix_socket", since = "1.10.0")]
671 impl<'a> io::Write for &'a UnixStream {
672 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
676 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
677 self.0.write_vectored(bufs)
681 fn is_write_vectored(&self) -> bool {
682 self.0.is_write_vectored()
685 fn flush(&mut self) -> io::Result<()> {
690 #[stable(feature = "unix_socket", since = "1.10.0")]
691 impl AsRawFd for UnixStream {
693 fn as_raw_fd(&self) -> RawFd {
698 #[stable(feature = "unix_socket", since = "1.10.0")]
699 impl FromRawFd for UnixStream {
701 unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
702 UnixStream(Socket::from_inner(FromInner::from_inner(OwnedFd::from_raw_fd(fd))))
706 #[stable(feature = "unix_socket", since = "1.10.0")]
707 impl IntoRawFd for UnixStream {
709 fn into_raw_fd(self) -> RawFd {
714 #[stable(feature = "io_safety", since = "1.63.0")]
715 impl AsFd for UnixStream {
717 fn as_fd(&self) -> BorrowedFd<'_> {
722 #[stable(feature = "io_safety", since = "1.63.0")]
723 impl From<UnixStream> for OwnedFd {
725 fn from(unix_stream: UnixStream) -> OwnedFd {
726 unsafe { OwnedFd::from_raw_fd(unix_stream.into_raw_fd()) }
730 #[stable(feature = "io_safety", since = "1.63.0")]
731 impl From<OwnedFd> for UnixStream {
733 fn from(owned: OwnedFd) -> Self {
734 unsafe { Self::from_raw_fd(owned.into_raw_fd()) }