1 #![stable(feature = "unix_socket", since = "1.10.0")]
3 //! Unix-specific networking functionality
5 // FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
7 #[allow(non_camel_case_types)]
10 pub type socklen_t = u32;
13 pub struct sockaddr_un;
17 use crate::ffi::OsStr;
19 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
21 use crate::net::{self, Shutdown};
22 use crate::os::unix::ffi::OsStrExt;
23 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
24 use crate::path::Path;
25 use crate::sys::net::Socket;
26 use crate::sys::{self, cvt};
27 use crate::sys_common::{self, AsInner, FromInner, IntoInner};
28 use crate::time::Duration;
32 target_os = "android",
33 target_os = "dragonfly",
34 target_os = "freebsd",
35 target_os = "openbsd",
39 use libc::MSG_NOSIGNAL;
42 target_os = "android",
43 target_os = "dragonfly",
44 target_os = "freebsd",
45 target_os = "openbsd",
49 const MSG_NOSIGNAL: libc::c_int = 0x0;
51 fn sun_path_offset(addr: &libc::sockaddr_un) -> usize {
52 // Work with an actual instance of the type since using a null pointer is UB
53 let base = addr as *const _ as usize;
54 let path = &addr.sun_path as *const _ as usize;
58 unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
59 let mut addr: libc::sockaddr_un = mem::zeroed();
60 addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
62 let bytes = path.as_os_str().as_bytes();
64 if bytes.contains(&0) {
65 return Err(io::Error::new(
66 io::ErrorKind::InvalidInput,
67 "paths may not contain interior null bytes",
71 if bytes.len() >= addr.sun_path.len() {
72 return Err(io::Error::new(
73 io::ErrorKind::InvalidInput,
74 "path must be shorter than SUN_LEN",
77 for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
78 *dst = *src as libc::c_char;
80 // null byte for pathname addresses is already there because we zeroed the
83 let mut len = sun_path_offset(&addr) + bytes.len();
88 Ok((addr, len as libc::socklen_t))
91 enum AddressKind<'a> {
97 /// An address associated with a Unix socket.
102 /// use std::os::unix::net::UnixListener;
104 /// let socket = match UnixListener::bind("/tmp/sock") {
105 /// Ok(sock) => sock,
107 /// println!("Couldn't bind: {:?}", e);
111 /// let addr = socket.local_addr().expect("Couldn't get local address");
114 #[stable(feature = "unix_socket", since = "1.10.0")]
115 pub struct SocketAddr {
116 addr: libc::sockaddr_un,
117 len: libc::socklen_t,
121 fn new<F>(f: F) -> io::Result<SocketAddr>
123 F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int,
126 let mut addr: libc::sockaddr_un = mem::zeroed();
127 let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
128 cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
129 SocketAddr::from_parts(addr, len)
133 fn from_parts(addr: libc::sockaddr_un, mut len: libc::socklen_t) -> io::Result<SocketAddr> {
135 // When there is a datagram from unnamed unix socket
136 // linux returns zero bytes of address
137 len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address
138 } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
139 return Err(io::Error::new(
140 io::ErrorKind::InvalidInput,
141 "file descriptor did not correspond to a Unix socket",
145 Ok(SocketAddr { addr, len })
148 /// Returns `true` if the address is unnamed.
155 /// use std::os::unix::net::UnixListener;
157 /// fn main() -> std::io::Result<()> {
158 /// let socket = UnixListener::bind("/tmp/sock")?;
159 /// let addr = socket.local_addr().expect("Couldn't get local address");
160 /// assert_eq!(addr.is_unnamed(), false);
165 /// An unnamed address:
168 /// use std::os::unix::net::UnixDatagram;
170 /// fn main() -> std::io::Result<()> {
171 /// let socket = UnixDatagram::unbound()?;
172 /// let addr = socket.local_addr().expect("Couldn't get local address");
173 /// assert_eq!(addr.is_unnamed(), true);
177 #[stable(feature = "unix_socket", since = "1.10.0")]
178 pub fn is_unnamed(&self) -> bool {
179 if let AddressKind::Unnamed = self.address() { true } else { false }
182 /// Returns the contents of this address if it is a `pathname` address.
189 /// use std::os::unix::net::UnixListener;
190 /// use std::path::Path;
192 /// fn main() -> std::io::Result<()> {
193 /// let socket = UnixListener::bind("/tmp/sock")?;
194 /// let addr = socket.local_addr().expect("Couldn't get local address");
195 /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
200 /// Without a pathname:
203 /// use std::os::unix::net::UnixDatagram;
205 /// fn main() -> std::io::Result<()> {
206 /// let socket = UnixDatagram::unbound()?;
207 /// let addr = socket.local_addr().expect("Couldn't get local address");
208 /// assert_eq!(addr.as_pathname(), None);
212 #[stable(feature = "unix_socket", since = "1.10.0")]
213 pub fn as_pathname(&self) -> Option<&Path> {
214 if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
217 fn address(&self) -> AddressKind<'_> {
218 let len = self.len as usize - sun_path_offset(&self.addr);
219 let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
221 // macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
223 || (cfg!(not(any(target_os = "linux", target_os = "android")))
224 && self.addr.sun_path[0] == 0)
227 } else if self.addr.sun_path[0] == 0 {
228 AddressKind::Abstract(&path[1..len])
230 AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
235 #[stable(feature = "unix_socket", since = "1.10.0")]
236 impl fmt::Debug for SocketAddr {
237 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
238 match self.address() {
239 AddressKind::Unnamed => write!(fmt, "(unnamed)"),
240 AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
241 AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
246 struct AsciiEscaped<'a>(&'a [u8]);
248 impl<'a> fmt::Display for AsciiEscaped<'a> {
249 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
251 for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
252 write!(fmt, "{}", byte as char)?;
258 /// A Unix stream socket.
263 /// use std::os::unix::net::UnixStream;
264 /// use std::io::prelude::*;
266 /// fn main() -> std::io::Result<()> {
267 /// let mut stream = UnixStream::connect("/path/to/my/socket")?;
268 /// stream.write_all(b"hello world")?;
269 /// let mut response = String::new();
270 /// stream.read_to_string(&mut response)?;
271 /// println!("{}", response);
275 #[stable(feature = "unix_socket", since = "1.10.0")]
276 pub struct UnixStream(Socket);
278 #[stable(feature = "unix_socket", since = "1.10.0")]
279 impl fmt::Debug for UnixStream {
280 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
281 let mut builder = fmt.debug_struct("UnixStream");
282 builder.field("fd", self.0.as_inner());
283 if let Ok(addr) = self.local_addr() {
284 builder.field("local", &addr);
286 if let Ok(addr) = self.peer_addr() {
287 builder.field("peer", &addr);
294 /// Connects to the socket named by `path`.
299 /// use std::os::unix::net::UnixStream;
301 /// let socket = match UnixStream::connect("/tmp/sock") {
302 /// Ok(sock) => sock,
304 /// println!("Couldn't connect: {:?}", e);
309 #[stable(feature = "unix_socket", since = "1.10.0")]
310 pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
311 fn inner(path: &Path) -> io::Result<UnixStream> {
313 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
314 let (addr, len) = sockaddr_un(path)?;
316 cvt(libc::connect(*inner.as_inner(), &addr as *const _ as *const _, len))?;
317 Ok(UnixStream(inner))
323 /// Creates an unnamed pair of connected sockets.
325 /// Returns two `UnixStream`s which are connected to each other.
330 /// use std::os::unix::net::UnixStream;
332 /// let (sock1, sock2) = match UnixStream::pair() {
333 /// Ok((sock1, sock2)) => (sock1, sock2),
335 /// println!("Couldn't create a pair of sockets: {:?}", e);
340 #[stable(feature = "unix_socket", since = "1.10.0")]
341 pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
342 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM)?;
343 Ok((UnixStream(i1), UnixStream(i2)))
346 /// Creates a new independently owned handle to the underlying socket.
348 /// The returned `UnixStream` is a reference to the same stream that this
349 /// object references. Both handles will read and write the same stream of
350 /// data, and options set on one stream will be propagated to the other
356 /// use std::os::unix::net::UnixStream;
358 /// fn main() -> std::io::Result<()> {
359 /// let socket = UnixStream::connect("/tmp/sock")?;
360 /// let sock_copy = socket.try_clone().expect("Couldn't clone socket");
364 #[stable(feature = "unix_socket", since = "1.10.0")]
365 pub fn try_clone(&self) -> io::Result<UnixStream> {
366 self.0.duplicate().map(UnixStream)
369 /// Returns the socket address of the local half of this connection.
374 /// use std::os::unix::net::UnixStream;
376 /// fn main() -> std::io::Result<()> {
377 /// let socket = UnixStream::connect("/tmp/sock")?;
378 /// let addr = socket.local_addr().expect("Couldn't get local address");
382 #[stable(feature = "unix_socket", since = "1.10.0")]
383 pub fn local_addr(&self) -> io::Result<SocketAddr> {
384 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
387 /// Returns the socket address of the remote half of this connection.
392 /// use std::os::unix::net::UnixStream;
394 /// fn main() -> std::io::Result<()> {
395 /// let socket = UnixStream::connect("/tmp/sock")?;
396 /// let addr = socket.peer_addr().expect("Couldn't get peer address");
400 #[stable(feature = "unix_socket", since = "1.10.0")]
401 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
402 SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
405 /// Sets the read timeout for the socket.
407 /// If the provided value is [`None`], then [`read`] calls will block
408 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
411 /// [`None`]: crate::option::Option::None
412 /// [`Err`]: crate::result::Result::Err
413 /// [`read`]: io::Read::read
418 /// use std::os::unix::net::UnixStream;
419 /// use std::time::Duration;
421 /// fn main() -> std::io::Result<()> {
422 /// let socket = UnixStream::connect("/tmp/sock")?;
423 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
428 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
433 /// use std::os::unix::net::UnixStream;
434 /// use std::time::Duration;
436 /// fn main() -> std::io::Result<()> {
437 /// let socket = UnixStream::connect("/tmp/sock")?;
438 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
439 /// let err = result.unwrap_err();
440 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
444 #[stable(feature = "unix_socket", since = "1.10.0")]
445 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
446 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
449 /// Sets the write timeout for the socket.
451 /// If the provided value is [`None`], then [`write`] calls will block
452 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
453 /// passed to this method.
455 /// [`None`]: crate::option::Option::None
456 /// [`Err`]: crate::result::Result::Err
457 /// [`read`]: io::Read::read
462 /// use std::os::unix::net::UnixStream;
463 /// use std::time::Duration;
465 /// fn main() -> std::io::Result<()> {
466 /// let socket = UnixStream::connect("/tmp/sock")?;
467 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
468 /// .expect("Couldn't set write timeout");
473 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
478 /// use std::net::UdpSocket;
479 /// use std::time::Duration;
481 /// fn main() -> std::io::Result<()> {
482 /// let socket = UdpSocket::bind("127.0.0.1:34254")?;
483 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
484 /// let err = result.unwrap_err();
485 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
489 #[stable(feature = "unix_socket", since = "1.10.0")]
490 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
491 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
494 /// Returns the read timeout of this socket.
499 /// use std::os::unix::net::UnixStream;
500 /// use std::time::Duration;
502 /// fn main() -> std::io::Result<()> {
503 /// let socket = UnixStream::connect("/tmp/sock")?;
504 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
505 /// assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
509 #[stable(feature = "unix_socket", since = "1.10.0")]
510 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
511 self.0.timeout(libc::SO_RCVTIMEO)
514 /// Returns the write timeout of this socket.
519 /// use std::os::unix::net::UnixStream;
520 /// use std::time::Duration;
522 /// fn main() -> std::io::Result<()> {
523 /// let socket = UnixStream::connect("/tmp/sock")?;
524 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
525 /// .expect("Couldn't set write timeout");
526 /// assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
530 #[stable(feature = "unix_socket", since = "1.10.0")]
531 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
532 self.0.timeout(libc::SO_SNDTIMEO)
535 /// Moves the socket into or out of nonblocking mode.
540 /// use std::os::unix::net::UnixStream;
542 /// fn main() -> std::io::Result<()> {
543 /// let socket = UnixStream::connect("/tmp/sock")?;
544 /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
548 #[stable(feature = "unix_socket", since = "1.10.0")]
549 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
550 self.0.set_nonblocking(nonblocking)
553 /// Returns the value of the `SO_ERROR` option.
558 /// use std::os::unix::net::UnixStream;
560 /// fn main() -> std::io::Result<()> {
561 /// let socket = UnixStream::connect("/tmp/sock")?;
562 /// if let Ok(Some(err)) = socket.take_error() {
563 /// println!("Got error: {:?}", err);
569 /// # Platform specific
570 /// On Redox this always returns `None`.
571 #[stable(feature = "unix_socket", since = "1.10.0")]
572 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
576 /// Shuts down the read, write, or both halves of this connection.
578 /// This function will cause all pending and future I/O calls on the
579 /// specified portions to immediately return with an appropriate value
580 /// (see the documentation of [`Shutdown`]).
585 /// use std::os::unix::net::UnixStream;
586 /// use std::net::Shutdown;
588 /// fn main() -> std::io::Result<()> {
589 /// let socket = UnixStream::connect("/tmp/sock")?;
590 /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
594 #[stable(feature = "unix_socket", since = "1.10.0")]
595 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
600 #[stable(feature = "unix_socket", since = "1.10.0")]
601 impl io::Read for UnixStream {
602 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
603 io::Read::read(&mut &*self, buf)
606 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
607 io::Read::read_vectored(&mut &*self, bufs)
611 fn is_read_vectored(&self) -> bool {
612 io::Read::is_read_vectored(&&*self)
616 unsafe fn initializer(&self) -> Initializer {
621 #[stable(feature = "unix_socket", since = "1.10.0")]
622 impl<'a> io::Read for &'a UnixStream {
623 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
627 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
628 self.0.read_vectored(bufs)
632 fn is_read_vectored(&self) -> bool {
633 self.0.is_read_vectored()
637 unsafe fn initializer(&self) -> Initializer {
642 #[stable(feature = "unix_socket", since = "1.10.0")]
643 impl io::Write for UnixStream {
644 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
645 io::Write::write(&mut &*self, buf)
648 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
649 io::Write::write_vectored(&mut &*self, bufs)
653 fn is_write_vectored(&self) -> bool {
654 io::Write::is_write_vectored(&&*self)
657 fn flush(&mut self) -> io::Result<()> {
658 io::Write::flush(&mut &*self)
662 #[stable(feature = "unix_socket", since = "1.10.0")]
663 impl<'a> io::Write for &'a UnixStream {
664 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
668 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
669 self.0.write_vectored(bufs)
673 fn is_write_vectored(&self) -> bool {
674 self.0.is_write_vectored()
677 fn flush(&mut self) -> io::Result<()> {
682 #[stable(feature = "unix_socket", since = "1.10.0")]
683 impl AsRawFd for UnixStream {
684 fn as_raw_fd(&self) -> RawFd {
689 #[stable(feature = "unix_socket", since = "1.10.0")]
690 impl FromRawFd for UnixStream {
691 unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
692 UnixStream(Socket::from_inner(fd))
696 #[stable(feature = "unix_socket", since = "1.10.0")]
697 impl IntoRawFd for UnixStream {
698 fn into_raw_fd(self) -> RawFd {
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl AsRawFd for net::TcpStream {
705 fn as_raw_fd(&self) -> RawFd {
706 *self.as_inner().socket().as_inner()
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl AsRawFd for net::TcpListener {
712 fn as_raw_fd(&self) -> RawFd {
713 *self.as_inner().socket().as_inner()
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl AsRawFd for net::UdpSocket {
719 fn as_raw_fd(&self) -> RawFd {
720 *self.as_inner().socket().as_inner()
724 #[stable(feature = "from_raw_os", since = "1.1.0")]
725 impl FromRawFd for net::TcpStream {
726 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
727 let socket = sys::net::Socket::from_inner(fd);
728 net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
732 #[stable(feature = "from_raw_os", since = "1.1.0")]
733 impl FromRawFd for net::TcpListener {
734 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
735 let socket = sys::net::Socket::from_inner(fd);
736 net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
740 #[stable(feature = "from_raw_os", since = "1.1.0")]
741 impl FromRawFd for net::UdpSocket {
742 unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
743 let socket = sys::net::Socket::from_inner(fd);
744 net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
748 #[stable(feature = "into_raw_os", since = "1.4.0")]
749 impl IntoRawFd for net::TcpStream {
750 fn into_raw_fd(self) -> RawFd {
751 self.into_inner().into_socket().into_inner()
754 #[stable(feature = "into_raw_os", since = "1.4.0")]
755 impl IntoRawFd for net::TcpListener {
756 fn into_raw_fd(self) -> RawFd {
757 self.into_inner().into_socket().into_inner()
760 #[stable(feature = "into_raw_os", since = "1.4.0")]
761 impl IntoRawFd for net::UdpSocket {
762 fn into_raw_fd(self) -> RawFd {
763 self.into_inner().into_socket().into_inner()
767 /// A structure representing a Unix domain socket server.
773 /// use std::os::unix::net::{UnixStream, UnixListener};
775 /// fn handle_client(stream: UnixStream) {
779 /// fn main() -> std::io::Result<()> {
780 /// let listener = UnixListener::bind("/path/to/the/socket")?;
782 /// // accept connections and process them, spawning a new thread for each one
783 /// for stream in listener.incoming() {
786 /// /* connection succeeded */
787 /// thread::spawn(|| handle_client(stream));
790 /// /* connection failed */
798 #[stable(feature = "unix_socket", since = "1.10.0")]
799 pub struct UnixListener(Socket);
801 #[stable(feature = "unix_socket", since = "1.10.0")]
802 impl fmt::Debug for UnixListener {
803 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
804 let mut builder = fmt.debug_struct("UnixListener");
805 builder.field("fd", self.0.as_inner());
806 if let Ok(addr) = self.local_addr() {
807 builder.field("local", &addr);
814 /// Creates a new `UnixListener` bound to the specified socket.
819 /// use std::os::unix::net::UnixListener;
821 /// let listener = match UnixListener::bind("/path/to/the/socket") {
822 /// Ok(sock) => sock,
824 /// println!("Couldn't connect: {:?}", e);
829 #[stable(feature = "unix_socket", since = "1.10.0")]
830 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
831 fn inner(path: &Path) -> io::Result<UnixListener> {
833 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
834 let (addr, len) = sockaddr_un(path)?;
836 cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len as _))?;
837 cvt(libc::listen(*inner.as_inner(), 128))?;
839 Ok(UnixListener(inner))
845 /// Accepts a new incoming connection to this listener.
847 /// This function will block the calling thread until a new Unix connection
848 /// is established. When established, the corresponding [`UnixStream`] and
849 /// the remote peer's address will be returned.
851 /// [`UnixStream`]: crate::os::unix::net::UnixStream
856 /// use std::os::unix::net::UnixListener;
858 /// fn main() -> std::io::Result<()> {
859 /// let listener = UnixListener::bind("/path/to/the/socket")?;
861 /// match listener.accept() {
862 /// Ok((socket, addr)) => println!("Got a client: {:?}", addr),
863 /// Err(e) => println!("accept function failed: {:?}", e),
868 #[stable(feature = "unix_socket", since = "1.10.0")]
869 pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
870 let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
871 let mut len = mem::size_of_val(&storage) as libc::socklen_t;
872 let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
873 let addr = SocketAddr::from_parts(storage, len)?;
874 Ok((UnixStream(sock), addr))
877 /// Creates a new independently owned handle to the underlying socket.
879 /// The returned `UnixListener` is a reference to the same socket that this
880 /// object references. Both handles can be used to accept incoming
881 /// connections and options set on one listener will affect the other.
886 /// use std::os::unix::net::UnixListener;
888 /// fn main() -> std::io::Result<()> {
889 /// let listener = UnixListener::bind("/path/to/the/socket")?;
890 /// let listener_copy = listener.try_clone().expect("try_clone failed");
894 #[stable(feature = "unix_socket", since = "1.10.0")]
895 pub fn try_clone(&self) -> io::Result<UnixListener> {
896 self.0.duplicate().map(UnixListener)
899 /// Returns the local socket address of this listener.
904 /// use std::os::unix::net::UnixListener;
906 /// fn main() -> std::io::Result<()> {
907 /// let listener = UnixListener::bind("/path/to/the/socket")?;
908 /// let addr = listener.local_addr().expect("Couldn't get local address");
912 #[stable(feature = "unix_socket", since = "1.10.0")]
913 pub fn local_addr(&self) -> io::Result<SocketAddr> {
914 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
917 /// Moves the socket into or out of nonblocking mode.
919 /// This will result in the `accept` operation becoming nonblocking,
920 /// i.e., immediately returning from their calls. If the IO operation is
921 /// successful, `Ok` is returned and no further action is required. If the
922 /// IO operation could not be completed and needs to be retried, an error
923 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
928 /// use std::os::unix::net::UnixListener;
930 /// fn main() -> std::io::Result<()> {
931 /// let listener = UnixListener::bind("/path/to/the/socket")?;
932 /// listener.set_nonblocking(true).expect("Couldn't set non blocking");
936 #[stable(feature = "unix_socket", since = "1.10.0")]
937 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
938 self.0.set_nonblocking(nonblocking)
941 /// Returns the value of the `SO_ERROR` option.
946 /// use std::os::unix::net::UnixListener;
948 /// fn main() -> std::io::Result<()> {
949 /// let listener = UnixListener::bind("/tmp/sock")?;
951 /// if let Ok(Some(err)) = listener.take_error() {
952 /// println!("Got error: {:?}", err);
958 /// # Platform specific
959 /// On Redox this always returns `None`.
960 #[stable(feature = "unix_socket", since = "1.10.0")]
961 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
965 /// Returns an iterator over incoming connections.
967 /// The iterator will never return [`None`] and will also not yield the
968 /// peer's [`SocketAddr`] structure.
970 /// [`None`]: crate::option::Option::None
976 /// use std::os::unix::net::{UnixStream, UnixListener};
978 /// fn handle_client(stream: UnixStream) {
982 /// fn main() -> std::io::Result<()> {
983 /// let listener = UnixListener::bind("/path/to/the/socket")?;
985 /// for stream in listener.incoming() {
988 /// thread::spawn(|| handle_client(stream));
998 #[stable(feature = "unix_socket", since = "1.10.0")]
999 pub fn incoming(&self) -> Incoming<'_> {
1000 Incoming { listener: self }
1004 #[stable(feature = "unix_socket", since = "1.10.0")]
1005 impl AsRawFd for UnixListener {
1006 fn as_raw_fd(&self) -> RawFd {
1011 #[stable(feature = "unix_socket", since = "1.10.0")]
1012 impl FromRawFd for UnixListener {
1013 unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
1014 UnixListener(Socket::from_inner(fd))
1018 #[stable(feature = "unix_socket", since = "1.10.0")]
1019 impl IntoRawFd for UnixListener {
1020 fn into_raw_fd(self) -> RawFd {
1025 #[stable(feature = "unix_socket", since = "1.10.0")]
1026 impl<'a> IntoIterator for &'a UnixListener {
1027 type Item = io::Result<UnixStream>;
1028 type IntoIter = Incoming<'a>;
1030 fn into_iter(self) -> Incoming<'a> {
1035 /// An iterator over incoming connections to a [`UnixListener`].
1037 /// It will never return [`None`].
1039 /// [`None`]: crate::option::Option::None
1044 /// use std::thread;
1045 /// use std::os::unix::net::{UnixStream, UnixListener};
1047 /// fn handle_client(stream: UnixStream) {
1051 /// fn main() -> std::io::Result<()> {
1052 /// let listener = UnixListener::bind("/path/to/the/socket")?;
1054 /// for stream in listener.incoming() {
1057 /// thread::spawn(|| handle_client(stream));
1068 #[stable(feature = "unix_socket", since = "1.10.0")]
1069 pub struct Incoming<'a> {
1070 listener: &'a UnixListener,
1073 #[stable(feature = "unix_socket", since = "1.10.0")]
1074 impl<'a> Iterator for Incoming<'a> {
1075 type Item = io::Result<UnixStream>;
1077 fn next(&mut self) -> Option<io::Result<UnixStream>> {
1078 Some(self.listener.accept().map(|s| s.0))
1081 fn size_hint(&self) -> (usize, Option<usize>) {
1086 /// A Unix datagram socket.
1091 /// use std::os::unix::net::UnixDatagram;
1093 /// fn main() -> std::io::Result<()> {
1094 /// let socket = UnixDatagram::bind("/path/to/my/socket")?;
1095 /// socket.send_to(b"hello world", "/path/to/other/socket")?;
1096 /// let mut buf = [0; 100];
1097 /// let (count, address) = socket.recv_from(&mut buf)?;
1098 /// println!("socket {:?} sent {:?}", address, &buf[..count]);
1102 #[stable(feature = "unix_socket", since = "1.10.0")]
1103 pub struct UnixDatagram(Socket);
1105 #[stable(feature = "unix_socket", since = "1.10.0")]
1106 impl fmt::Debug for UnixDatagram {
1107 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1108 let mut builder = fmt.debug_struct("UnixDatagram");
1109 builder.field("fd", self.0.as_inner());
1110 if let Ok(addr) = self.local_addr() {
1111 builder.field("local", &addr);
1113 if let Ok(addr) = self.peer_addr() {
1114 builder.field("peer", &addr);
1121 /// Creates a Unix datagram socket bound to the given path.
1126 /// use std::os::unix::net::UnixDatagram;
1128 /// let sock = match UnixDatagram::bind("/path/to/the/socket") {
1129 /// Ok(sock) => sock,
1131 /// println!("Couldn't bind: {:?}", e);
1136 #[stable(feature = "unix_socket", since = "1.10.0")]
1137 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
1138 fn inner(path: &Path) -> io::Result<UnixDatagram> {
1140 let socket = UnixDatagram::unbound()?;
1141 let (addr, len) = sockaddr_un(path)?;
1143 cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len as _))?;
1148 inner(path.as_ref())
1151 /// Creates a Unix Datagram socket which is not bound to any address.
1156 /// use std::os::unix::net::UnixDatagram;
1158 /// let sock = match UnixDatagram::unbound() {
1159 /// Ok(sock) => sock,
1161 /// println!("Couldn't unbound: {:?}", e);
1166 #[stable(feature = "unix_socket", since = "1.10.0")]
1167 pub fn unbound() -> io::Result<UnixDatagram> {
1168 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1169 Ok(UnixDatagram(inner))
1172 /// Creates an unnamed pair of connected sockets.
1174 /// Returns two `UnixDatagrams`s which are connected to each other.
1179 /// use std::os::unix::net::UnixDatagram;
1181 /// let (sock1, sock2) = match UnixDatagram::pair() {
1182 /// Ok((sock1, sock2)) => (sock1, sock2),
1184 /// println!("Couldn't unbound: {:?}", e);
1189 #[stable(feature = "unix_socket", since = "1.10.0")]
1190 pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
1191 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1192 Ok((UnixDatagram(i1), UnixDatagram(i2)))
1195 /// Connects the socket to the specified address.
1197 /// The [`send`] method may be used to send data to the specified address.
1198 /// [`recv`] and [`recv_from`] will only receive data from that address.
1200 /// [`send`]: UnixDatagram::send
1201 /// [`recv`]: UnixDatagram::recv
1202 /// [`recv_from`]: UnixDatagram::recv_from
1207 /// use std::os::unix::net::UnixDatagram;
1209 /// fn main() -> std::io::Result<()> {
1210 /// let sock = UnixDatagram::unbound()?;
1211 /// match sock.connect("/path/to/the/socket") {
1212 /// Ok(sock) => sock,
1214 /// println!("Couldn't connect: {:?}", e);
1221 #[stable(feature = "unix_socket", since = "1.10.0")]
1222 pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1223 fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
1225 let (addr, len) = sockaddr_un(path)?;
1227 cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len))?;
1232 inner(self, path.as_ref())
1235 /// Creates a new independently owned handle to the underlying socket.
1237 /// The returned `UnixDatagram` is a reference to the same socket that this
1238 /// object references. Both handles can be used to accept incoming
1239 /// connections and options set on one side will affect the other.
1244 /// use std::os::unix::net::UnixDatagram;
1246 /// fn main() -> std::io::Result<()> {
1247 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1248 /// let sock_copy = sock.try_clone().expect("try_clone failed");
1252 #[stable(feature = "unix_socket", since = "1.10.0")]
1253 pub fn try_clone(&self) -> io::Result<UnixDatagram> {
1254 self.0.duplicate().map(UnixDatagram)
1257 /// Returns the address of this socket.
1262 /// use std::os::unix::net::UnixDatagram;
1264 /// fn main() -> std::io::Result<()> {
1265 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1266 /// let addr = sock.local_addr().expect("Couldn't get local address");
1270 #[stable(feature = "unix_socket", since = "1.10.0")]
1271 pub fn local_addr(&self) -> io::Result<SocketAddr> {
1272 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
1275 /// Returns the address of this socket's peer.
1277 /// The [`connect`] method will connect the socket to a peer.
1279 /// [`connect`]: UnixDatagram::connect
1284 /// use std::os::unix::net::UnixDatagram;
1286 /// fn main() -> std::io::Result<()> {
1287 /// let sock = UnixDatagram::unbound()?;
1288 /// sock.connect("/path/to/the/socket")?;
1290 /// let addr = sock.peer_addr().expect("Couldn't get peer address");
1294 #[stable(feature = "unix_socket", since = "1.10.0")]
1295 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
1296 SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
1299 /// Receives data from the socket.
1301 /// On success, returns the number of bytes read and the address from
1302 /// whence the data came.
1307 /// use std::os::unix::net::UnixDatagram;
1309 /// fn main() -> std::io::Result<()> {
1310 /// let sock = UnixDatagram::unbound()?;
1311 /// let mut buf = vec![0; 10];
1312 /// let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
1313 /// println!("received {} bytes from {:?}", size, sender);
1317 #[stable(feature = "unix_socket", since = "1.10.0")]
1318 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1320 let addr = SocketAddr::new(|addr, len| unsafe {
1321 count = libc::recvfrom(
1323 buf.as_mut_ptr() as *mut _,
1331 } else if count == 0 {
1338 Ok((count as usize, addr))
1341 /// Receives data from the socket.
1343 /// On success, returns the number of bytes read.
1348 /// use std::os::unix::net::UnixDatagram;
1350 /// fn main() -> std::io::Result<()> {
1351 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1352 /// let mut buf = vec![0; 10];
1353 /// sock.recv(buf.as_mut_slice()).expect("recv function failed");
1357 #[stable(feature = "unix_socket", since = "1.10.0")]
1358 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1362 /// Sends data on the socket to the specified address.
1364 /// On success, returns the number of bytes written.
1369 /// use std::os::unix::net::UnixDatagram;
1371 /// fn main() -> std::io::Result<()> {
1372 /// let sock = UnixDatagram::unbound()?;
1373 /// sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
1377 #[stable(feature = "unix_socket", since = "1.10.0")]
1378 pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
1379 fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
1381 let (addr, len) = sockaddr_un(path)?;
1383 let count = cvt(libc::sendto(
1385 buf.as_ptr() as *const _,
1388 &addr as *const _ as *const _,
1394 inner(self, buf, path.as_ref())
1397 /// Sends data on the socket to the socket's peer.
1399 /// The peer address may be set by the `connect` method, and this method
1400 /// will return an error if the socket has not already been connected.
1402 /// On success, returns the number of bytes written.
1407 /// use std::os::unix::net::UnixDatagram;
1409 /// fn main() -> std::io::Result<()> {
1410 /// let sock = UnixDatagram::unbound()?;
1411 /// sock.connect("/some/sock").expect("Couldn't connect");
1412 /// sock.send(b"omelette au fromage").expect("send_to function failed");
1416 #[stable(feature = "unix_socket", since = "1.10.0")]
1417 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
1421 /// Sets the read timeout for the socket.
1423 /// If the provided value is [`None`], then [`recv`] and [`recv_from`] calls will
1424 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`]
1425 /// is passed to this method.
1427 /// [`None`]: crate::option::Option::None
1428 /// [`Err`]: crate::result::Result::Err
1429 /// [`recv`]: UnixDatagram::recv
1430 /// [`recv_from`]: UnixDatagram::recv_from
1435 /// use std::os::unix::net::UnixDatagram;
1436 /// use std::time::Duration;
1438 /// fn main() -> std::io::Result<()> {
1439 /// let sock = UnixDatagram::unbound()?;
1440 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1441 /// .expect("set_read_timeout function failed");
1446 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1451 /// use std::os::unix::net::UnixDatagram;
1452 /// use std::time::Duration;
1454 /// fn main() -> std::io::Result<()> {
1455 /// let socket = UnixDatagram::unbound()?;
1456 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1457 /// let err = result.unwrap_err();
1458 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1462 #[stable(feature = "unix_socket", since = "1.10.0")]
1463 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1464 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
1467 /// Sets the write timeout for the socket.
1469 /// If the provided value is [`None`], then [`send`] and [`send_to`] calls will
1470 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
1473 /// [`None`]: crate::option::Option::None
1474 /// [`send`]: UnixDatagram::send
1475 /// [`send_to`]: UnixDatagram::send_to
1480 /// use std::os::unix::net::UnixDatagram;
1481 /// use std::time::Duration;
1483 /// fn main() -> std::io::Result<()> {
1484 /// let sock = UnixDatagram::unbound()?;
1485 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1486 /// .expect("set_write_timeout function failed");
1491 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1496 /// use std::os::unix::net::UnixDatagram;
1497 /// use std::time::Duration;
1499 /// fn main() -> std::io::Result<()> {
1500 /// let socket = UnixDatagram::unbound()?;
1501 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1502 /// let err = result.unwrap_err();
1503 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1507 #[stable(feature = "unix_socket", since = "1.10.0")]
1508 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1509 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
1512 /// Returns the read timeout of this socket.
1517 /// use std::os::unix::net::UnixDatagram;
1518 /// use std::time::Duration;
1520 /// fn main() -> std::io::Result<()> {
1521 /// let sock = UnixDatagram::unbound()?;
1522 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1523 /// .expect("set_read_timeout function failed");
1524 /// assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
1528 #[stable(feature = "unix_socket", since = "1.10.0")]
1529 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
1530 self.0.timeout(libc::SO_RCVTIMEO)
1533 /// Returns the write timeout of this socket.
1538 /// use std::os::unix::net::UnixDatagram;
1539 /// use std::time::Duration;
1541 /// fn main() -> std::io::Result<()> {
1542 /// let sock = UnixDatagram::unbound()?;
1543 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1544 /// .expect("set_write_timeout function failed");
1545 /// assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
1549 #[stable(feature = "unix_socket", since = "1.10.0")]
1550 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
1551 self.0.timeout(libc::SO_SNDTIMEO)
1554 /// Moves the socket into or out of nonblocking mode.
1559 /// use std::os::unix::net::UnixDatagram;
1561 /// fn main() -> std::io::Result<()> {
1562 /// let sock = UnixDatagram::unbound()?;
1563 /// sock.set_nonblocking(true).expect("set_nonblocking function failed");
1567 #[stable(feature = "unix_socket", since = "1.10.0")]
1568 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1569 self.0.set_nonblocking(nonblocking)
1572 /// Returns the value of the `SO_ERROR` option.
1577 /// use std::os::unix::net::UnixDatagram;
1579 /// fn main() -> std::io::Result<()> {
1580 /// let sock = UnixDatagram::unbound()?;
1581 /// if let Ok(Some(err)) = sock.take_error() {
1582 /// println!("Got error: {:?}", err);
1587 #[stable(feature = "unix_socket", since = "1.10.0")]
1588 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1592 /// Shut down the read, write, or both halves of this connection.
1594 /// This function will cause all pending and future I/O calls on the
1595 /// specified portions to immediately return with an appropriate value
1596 /// (see the documentation of [`Shutdown`]).
1599 /// use std::os::unix::net::UnixDatagram;
1600 /// use std::net::Shutdown;
1602 /// fn main() -> std::io::Result<()> {
1603 /// let sock = UnixDatagram::unbound()?;
1604 /// sock.shutdown(Shutdown::Both).expect("shutdown function failed");
1608 #[stable(feature = "unix_socket", since = "1.10.0")]
1609 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
1610 self.0.shutdown(how)
1614 #[stable(feature = "unix_socket", since = "1.10.0")]
1615 impl AsRawFd for UnixDatagram {
1616 fn as_raw_fd(&self) -> RawFd {
1621 #[stable(feature = "unix_socket", since = "1.10.0")]
1622 impl FromRawFd for UnixDatagram {
1623 unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
1624 UnixDatagram(Socket::from_inner(fd))
1628 #[stable(feature = "unix_socket", since = "1.10.0")]
1629 impl IntoRawFd for UnixDatagram {
1630 fn into_raw_fd(self) -> RawFd {
1635 #[cfg(all(test, not(target_os = "emscripten")))]
1637 use crate::io::prelude::*;
1638 use crate::io::{self, ErrorKind};
1639 use crate::sys_common::io::test::tmpdir;
1641 use crate::time::Duration;
1645 macro_rules! or_panic {
1649 Err(e) => panic!("{}", e),
1657 let socket_path = dir.path().join("sock");
1658 let msg1 = b"hello";
1659 let msg2 = b"world!";
1661 let listener = or_panic!(UnixListener::bind(&socket_path));
1662 let thread = thread::spawn(move || {
1663 let mut stream = or_panic!(listener.accept()).0;
1664 let mut buf = [0; 5];
1665 or_panic!(stream.read(&mut buf));
1666 assert_eq!(&msg1[..], &buf[..]);
1667 or_panic!(stream.write_all(msg2));
1670 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1671 assert_eq!(Some(&*socket_path), stream.peer_addr().unwrap().as_pathname());
1672 or_panic!(stream.write_all(msg1));
1673 let mut buf = vec![];
1674 or_panic!(stream.read_to_end(&mut buf));
1675 assert_eq!(&msg2[..], &buf[..]);
1678 thread.join().unwrap();
1683 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1685 let len = or_panic!(s1.write_vectored(&[
1686 IoSlice::new(b"hello"),
1688 IoSlice::new(b"world!")
1690 assert_eq!(len, 12);
1692 let mut buf1 = [0; 6];
1693 let mut buf2 = [0; 7];
1694 let len = or_panic!(
1695 s2.read_vectored(&mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)],)
1697 assert_eq!(len, 12);
1698 assert_eq!(&buf1, b"hello ");
1699 assert_eq!(&buf2, b"world!\0");
1704 let msg1 = b"hello";
1705 let msg2 = b"world!";
1707 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1708 let thread = thread::spawn(move || {
1709 // s1 must be moved in or the test will hang!
1710 let mut buf = [0; 5];
1711 or_panic!(s1.read(&mut buf));
1712 assert_eq!(&msg1[..], &buf[..]);
1713 or_panic!(s1.write_all(msg2));
1716 or_panic!(s2.write_all(msg1));
1717 let mut buf = vec![];
1718 or_panic!(s2.read_to_end(&mut buf));
1719 assert_eq!(&msg2[..], &buf[..]);
1722 thread.join().unwrap();
1728 let socket_path = dir.path().join("sock");
1729 let msg1 = b"hello";
1730 let msg2 = b"world";
1732 let listener = or_panic!(UnixListener::bind(&socket_path));
1733 let thread = thread::spawn(move || {
1734 let mut stream = or_panic!(listener.accept()).0;
1735 or_panic!(stream.write_all(msg1));
1736 or_panic!(stream.write_all(msg2));
1739 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1740 let mut stream2 = or_panic!(stream.try_clone());
1742 let mut buf = [0; 5];
1743 or_panic!(stream.read(&mut buf));
1744 assert_eq!(&msg1[..], &buf[..]);
1745 or_panic!(stream2.read(&mut buf));
1746 assert_eq!(&msg2[..], &buf[..]);
1748 thread.join().unwrap();
1754 let socket_path = dir.path().join("sock");
1756 let listener = or_panic!(UnixListener::bind(&socket_path));
1757 let thread = thread::spawn(move || {
1758 for stream in listener.incoming().take(2) {
1759 let mut stream = or_panic!(stream);
1761 or_panic!(stream.read(&mut buf));
1766 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1767 or_panic!(stream.write_all(&[0]));
1770 thread.join().unwrap();
1776 let socket_path = dir.path().join(
1777 "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
1778 sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf",
1780 match UnixStream::connect(&socket_path) {
1781 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1782 Err(e) => panic!("unexpected error {}", e),
1783 Ok(_) => panic!("unexpected success"),
1786 match UnixListener::bind(&socket_path) {
1787 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1788 Err(e) => panic!("unexpected error {}", e),
1789 Ok(_) => panic!("unexpected success"),
1792 match UnixDatagram::bind(&socket_path) {
1793 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1794 Err(e) => panic!("unexpected error {}", e),
1795 Ok(_) => panic!("unexpected success"),
1802 let socket_path = dir.path().join("sock");
1804 let _listener = or_panic!(UnixListener::bind(&socket_path));
1806 let stream = or_panic!(UnixStream::connect(&socket_path));
1807 let dur = Duration::new(15410, 0);
1809 assert_eq!(None, or_panic!(stream.read_timeout()));
1811 or_panic!(stream.set_read_timeout(Some(dur)));
1812 assert_eq!(Some(dur), or_panic!(stream.read_timeout()));
1814 assert_eq!(None, or_panic!(stream.write_timeout()));
1816 or_panic!(stream.set_write_timeout(Some(dur)));
1817 assert_eq!(Some(dur), or_panic!(stream.write_timeout()));
1819 or_panic!(stream.set_read_timeout(None));
1820 assert_eq!(None, or_panic!(stream.read_timeout()));
1822 or_panic!(stream.set_write_timeout(None));
1823 assert_eq!(None, or_panic!(stream.write_timeout()));
1827 fn test_read_timeout() {
1829 let socket_path = dir.path().join("sock");
1831 let _listener = or_panic!(UnixListener::bind(&socket_path));
1833 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1834 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1836 let mut buf = [0; 10];
1837 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1839 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1840 "unexpected_error: {:?}",
1846 fn test_read_with_timeout() {
1848 let socket_path = dir.path().join("sock");
1850 let listener = or_panic!(UnixListener::bind(&socket_path));
1852 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1853 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1855 let mut other_end = or_panic!(listener.accept()).0;
1856 or_panic!(other_end.write_all(b"hello world"));
1858 let mut buf = [0; 11];
1859 or_panic!(stream.read(&mut buf));
1860 assert_eq!(b"hello world", &buf[..]);
1862 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1864 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1865 "unexpected_error: {:?}",
1870 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1871 // when passed zero Durations
1873 fn test_unix_stream_timeout_zero_duration() {
1875 let socket_path = dir.path().join("sock");
1877 let listener = or_panic!(UnixListener::bind(&socket_path));
1878 let stream = or_panic!(UnixStream::connect(&socket_path));
1880 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1881 let err = result.unwrap_err();
1882 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1884 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1885 let err = result.unwrap_err();
1886 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1892 fn test_unix_datagram() {
1894 let path1 = dir.path().join("sock1");
1895 let path2 = dir.path().join("sock2");
1897 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1898 let sock2 = or_panic!(UnixDatagram::bind(&path2));
1900 let msg = b"hello world";
1901 or_panic!(sock1.send_to(msg, &path2));
1902 let mut buf = [0; 11];
1903 or_panic!(sock2.recv_from(&mut buf));
1904 assert_eq!(msg, &buf[..]);
1908 fn test_unnamed_unix_datagram() {
1910 let path1 = dir.path().join("sock1");
1912 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1913 let sock2 = or_panic!(UnixDatagram::unbound());
1915 let msg = b"hello world";
1916 or_panic!(sock2.send_to(msg, &path1));
1917 let mut buf = [0; 11];
1918 let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
1919 assert_eq!(usize, 11);
1920 assert!(addr.is_unnamed());
1921 assert_eq!(msg, &buf[..]);
1925 fn test_connect_unix_datagram() {
1927 let path1 = dir.path().join("sock1");
1928 let path2 = dir.path().join("sock2");
1930 let bsock1 = or_panic!(UnixDatagram::bind(&path1));
1931 let bsock2 = or_panic!(UnixDatagram::bind(&path2));
1932 let sock = or_panic!(UnixDatagram::unbound());
1933 or_panic!(sock.connect(&path1));
1936 let msg = b"hello there";
1937 or_panic!(sock.send(msg));
1938 let mut buf = [0; 11];
1939 let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
1940 assert_eq!(usize, 11);
1941 assert!(addr.is_unnamed());
1942 assert_eq!(msg, &buf[..]);
1944 // Changing default socket works too
1945 or_panic!(sock.connect(&path2));
1946 or_panic!(sock.send(msg));
1947 or_panic!(bsock2.recv_from(&mut buf));
1951 fn test_unix_datagram_recv() {
1953 let path1 = dir.path().join("sock1");
1955 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1956 let sock2 = or_panic!(UnixDatagram::unbound());
1957 or_panic!(sock2.connect(&path1));
1959 let msg = b"hello world";
1960 or_panic!(sock2.send(msg));
1961 let mut buf = [0; 11];
1962 let size = or_panic!(sock1.recv(&mut buf));
1963 assert_eq!(size, 11);
1964 assert_eq!(msg, &buf[..]);
1968 fn datagram_pair() {
1969 let msg1 = b"hello";
1970 let msg2 = b"world!";
1972 let (s1, s2) = or_panic!(UnixDatagram::pair());
1973 let thread = thread::spawn(move || {
1974 // s1 must be moved in or the test will hang!
1975 let mut buf = [0; 5];
1976 or_panic!(s1.recv(&mut buf));
1977 assert_eq!(&msg1[..], &buf[..]);
1978 or_panic!(s1.send(msg2));
1981 or_panic!(s2.send(msg1));
1982 let mut buf = [0; 6];
1983 or_panic!(s2.recv(&mut buf));
1984 assert_eq!(&msg2[..], &buf[..]);
1987 thread.join().unwrap();
1990 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1991 // when passed zero Durations
1993 fn test_unix_datagram_timeout_zero_duration() {
1995 let path = dir.path().join("sock");
1997 let datagram = or_panic!(UnixDatagram::bind(&path));
1999 let result = datagram.set_write_timeout(Some(Duration::new(0, 0)));
2000 let err = result.unwrap_err();
2001 assert_eq!(err.kind(), ErrorKind::InvalidInput);
2003 let result = datagram.set_read_timeout(Some(Duration::new(0, 0)));
2004 let err = result.unwrap_err();
2005 assert_eq!(err.kind(), ErrorKind::InvalidInput);
2009 fn abstract_namespace_not_allowed() {
2010 assert!(UnixStream::connect("\0asdf").is_err());