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 /// [`read`]: io::Read::read
416 /// use std::os::unix::net::UnixStream;
417 /// use std::time::Duration;
419 /// fn main() -> std::io::Result<()> {
420 /// let socket = UnixStream::connect("/tmp/sock")?;
421 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
426 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
431 /// use std::os::unix::net::UnixStream;
432 /// use std::time::Duration;
434 /// fn main() -> std::io::Result<()> {
435 /// let socket = UnixStream::connect("/tmp/sock")?;
436 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
437 /// let err = result.unwrap_err();
438 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
442 #[stable(feature = "unix_socket", since = "1.10.0")]
443 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
444 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
447 /// Sets the write timeout for the socket.
449 /// If the provided value is [`None`], then [`write`] calls will block
450 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
451 /// passed to this method.
453 /// [`read`]: io::Read::read
458 /// use std::os::unix::net::UnixStream;
459 /// use std::time::Duration;
461 /// fn main() -> std::io::Result<()> {
462 /// let socket = UnixStream::connect("/tmp/sock")?;
463 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
464 /// .expect("Couldn't set write timeout");
469 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
474 /// use std::net::UdpSocket;
475 /// use std::time::Duration;
477 /// fn main() -> std::io::Result<()> {
478 /// let socket = UdpSocket::bind("127.0.0.1:34254")?;
479 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
480 /// let err = result.unwrap_err();
481 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
485 #[stable(feature = "unix_socket", since = "1.10.0")]
486 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
487 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
490 /// Returns the read timeout of this socket.
495 /// use std::os::unix::net::UnixStream;
496 /// use std::time::Duration;
498 /// fn main() -> std::io::Result<()> {
499 /// let socket = UnixStream::connect("/tmp/sock")?;
500 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
501 /// assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
505 #[stable(feature = "unix_socket", since = "1.10.0")]
506 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
507 self.0.timeout(libc::SO_RCVTIMEO)
510 /// Returns the write timeout of this socket.
515 /// use std::os::unix::net::UnixStream;
516 /// use std::time::Duration;
518 /// fn main() -> std::io::Result<()> {
519 /// let socket = UnixStream::connect("/tmp/sock")?;
520 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
521 /// .expect("Couldn't set write timeout");
522 /// assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
526 #[stable(feature = "unix_socket", since = "1.10.0")]
527 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
528 self.0.timeout(libc::SO_SNDTIMEO)
531 /// Moves the socket into or out of nonblocking mode.
536 /// use std::os::unix::net::UnixStream;
538 /// fn main() -> std::io::Result<()> {
539 /// let socket = UnixStream::connect("/tmp/sock")?;
540 /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
544 #[stable(feature = "unix_socket", since = "1.10.0")]
545 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
546 self.0.set_nonblocking(nonblocking)
549 /// Returns the value of the `SO_ERROR` option.
554 /// use std::os::unix::net::UnixStream;
556 /// fn main() -> std::io::Result<()> {
557 /// let socket = UnixStream::connect("/tmp/sock")?;
558 /// if let Ok(Some(err)) = socket.take_error() {
559 /// println!("Got error: {:?}", err);
565 /// # Platform specific
566 /// On Redox this always returns `None`.
567 #[stable(feature = "unix_socket", since = "1.10.0")]
568 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
572 /// Shuts down the read, write, or both halves of this connection.
574 /// This function will cause all pending and future I/O calls on the
575 /// specified portions to immediately return with an appropriate value
576 /// (see the documentation of [`Shutdown`]).
581 /// use std::os::unix::net::UnixStream;
582 /// use std::net::Shutdown;
584 /// fn main() -> std::io::Result<()> {
585 /// let socket = UnixStream::connect("/tmp/sock")?;
586 /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
590 #[stable(feature = "unix_socket", since = "1.10.0")]
591 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
596 #[stable(feature = "unix_socket", since = "1.10.0")]
597 impl io::Read for UnixStream {
598 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
599 io::Read::read(&mut &*self, buf)
602 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
603 io::Read::read_vectored(&mut &*self, bufs)
607 fn is_read_vectored(&self) -> bool {
608 io::Read::is_read_vectored(&&*self)
612 unsafe fn initializer(&self) -> Initializer {
617 #[stable(feature = "unix_socket", since = "1.10.0")]
618 impl<'a> io::Read for &'a UnixStream {
619 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
623 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
624 self.0.read_vectored(bufs)
628 fn is_read_vectored(&self) -> bool {
629 self.0.is_read_vectored()
633 unsafe fn initializer(&self) -> Initializer {
638 #[stable(feature = "unix_socket", since = "1.10.0")]
639 impl io::Write for UnixStream {
640 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
641 io::Write::write(&mut &*self, buf)
644 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
645 io::Write::write_vectored(&mut &*self, bufs)
649 fn is_write_vectored(&self) -> bool {
650 io::Write::is_write_vectored(&&*self)
653 fn flush(&mut self) -> io::Result<()> {
654 io::Write::flush(&mut &*self)
658 #[stable(feature = "unix_socket", since = "1.10.0")]
659 impl<'a> io::Write for &'a UnixStream {
660 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
664 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
665 self.0.write_vectored(bufs)
669 fn is_write_vectored(&self) -> bool {
670 self.0.is_write_vectored()
673 fn flush(&mut self) -> io::Result<()> {
678 #[stable(feature = "unix_socket", since = "1.10.0")]
679 impl AsRawFd for UnixStream {
680 fn as_raw_fd(&self) -> RawFd {
685 #[stable(feature = "unix_socket", since = "1.10.0")]
686 impl FromRawFd for UnixStream {
687 unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
688 UnixStream(Socket::from_inner(fd))
692 #[stable(feature = "unix_socket", since = "1.10.0")]
693 impl IntoRawFd for UnixStream {
694 fn into_raw_fd(self) -> RawFd {
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl AsRawFd for net::TcpStream {
701 fn as_raw_fd(&self) -> RawFd {
702 *self.as_inner().socket().as_inner()
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl AsRawFd for net::TcpListener {
708 fn as_raw_fd(&self) -> RawFd {
709 *self.as_inner().socket().as_inner()
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl AsRawFd for net::UdpSocket {
715 fn as_raw_fd(&self) -> RawFd {
716 *self.as_inner().socket().as_inner()
720 #[stable(feature = "from_raw_os", since = "1.1.0")]
721 impl FromRawFd for net::TcpStream {
722 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
723 let socket = sys::net::Socket::from_inner(fd);
724 net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
728 #[stable(feature = "from_raw_os", since = "1.1.0")]
729 impl FromRawFd for net::TcpListener {
730 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
731 let socket = sys::net::Socket::from_inner(fd);
732 net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
736 #[stable(feature = "from_raw_os", since = "1.1.0")]
737 impl FromRawFd for net::UdpSocket {
738 unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
739 let socket = sys::net::Socket::from_inner(fd);
740 net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
744 #[stable(feature = "into_raw_os", since = "1.4.0")]
745 impl IntoRawFd for net::TcpStream {
746 fn into_raw_fd(self) -> RawFd {
747 self.into_inner().into_socket().into_inner()
750 #[stable(feature = "into_raw_os", since = "1.4.0")]
751 impl IntoRawFd for net::TcpListener {
752 fn into_raw_fd(self) -> RawFd {
753 self.into_inner().into_socket().into_inner()
756 #[stable(feature = "into_raw_os", since = "1.4.0")]
757 impl IntoRawFd for net::UdpSocket {
758 fn into_raw_fd(self) -> RawFd {
759 self.into_inner().into_socket().into_inner()
763 /// A structure representing a Unix domain socket server.
769 /// use std::os::unix::net::{UnixStream, UnixListener};
771 /// fn handle_client(stream: UnixStream) {
775 /// fn main() -> std::io::Result<()> {
776 /// let listener = UnixListener::bind("/path/to/the/socket")?;
778 /// // accept connections and process them, spawning a new thread for each one
779 /// for stream in listener.incoming() {
782 /// /* connection succeeded */
783 /// thread::spawn(|| handle_client(stream));
786 /// /* connection failed */
794 #[stable(feature = "unix_socket", since = "1.10.0")]
795 pub struct UnixListener(Socket);
797 #[stable(feature = "unix_socket", since = "1.10.0")]
798 impl fmt::Debug for UnixListener {
799 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
800 let mut builder = fmt.debug_struct("UnixListener");
801 builder.field("fd", self.0.as_inner());
802 if let Ok(addr) = self.local_addr() {
803 builder.field("local", &addr);
810 /// Creates a new `UnixListener` bound to the specified socket.
815 /// use std::os::unix::net::UnixListener;
817 /// let listener = match UnixListener::bind("/path/to/the/socket") {
818 /// Ok(sock) => sock,
820 /// println!("Couldn't connect: {:?}", e);
825 #[stable(feature = "unix_socket", since = "1.10.0")]
826 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
827 fn inner(path: &Path) -> io::Result<UnixListener> {
829 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
830 let (addr, len) = sockaddr_un(path)?;
832 cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len as _))?;
833 cvt(libc::listen(*inner.as_inner(), 128))?;
835 Ok(UnixListener(inner))
841 /// Accepts a new incoming connection to this listener.
843 /// This function will block the calling thread until a new Unix connection
844 /// is established. When established, the corresponding [`UnixStream`] and
845 /// the remote peer's address will be returned.
847 /// [`UnixStream`]: crate::os::unix::net::UnixStream
852 /// use std::os::unix::net::UnixListener;
854 /// fn main() -> std::io::Result<()> {
855 /// let listener = UnixListener::bind("/path/to/the/socket")?;
857 /// match listener.accept() {
858 /// Ok((socket, addr)) => println!("Got a client: {:?}", addr),
859 /// Err(e) => println!("accept function failed: {:?}", e),
864 #[stable(feature = "unix_socket", since = "1.10.0")]
865 pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
866 let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
867 let mut len = mem::size_of_val(&storage) as libc::socklen_t;
868 let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
869 let addr = SocketAddr::from_parts(storage, len)?;
870 Ok((UnixStream(sock), addr))
873 /// Creates a new independently owned handle to the underlying socket.
875 /// The returned `UnixListener` is a reference to the same socket that this
876 /// object references. Both handles can be used to accept incoming
877 /// connections and options set on one listener will affect the other.
882 /// use std::os::unix::net::UnixListener;
884 /// fn main() -> std::io::Result<()> {
885 /// let listener = UnixListener::bind("/path/to/the/socket")?;
886 /// let listener_copy = listener.try_clone().expect("try_clone failed");
890 #[stable(feature = "unix_socket", since = "1.10.0")]
891 pub fn try_clone(&self) -> io::Result<UnixListener> {
892 self.0.duplicate().map(UnixListener)
895 /// Returns the local socket address of this listener.
900 /// use std::os::unix::net::UnixListener;
902 /// fn main() -> std::io::Result<()> {
903 /// let listener = UnixListener::bind("/path/to/the/socket")?;
904 /// let addr = listener.local_addr().expect("Couldn't get local address");
908 #[stable(feature = "unix_socket", since = "1.10.0")]
909 pub fn local_addr(&self) -> io::Result<SocketAddr> {
910 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
913 /// Moves the socket into or out of nonblocking mode.
915 /// This will result in the `accept` operation becoming nonblocking,
916 /// i.e., immediately returning from their calls. If the IO operation is
917 /// successful, `Ok` is returned and no further action is required. If the
918 /// IO operation could not be completed and needs to be retried, an error
919 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
924 /// use std::os::unix::net::UnixListener;
926 /// fn main() -> std::io::Result<()> {
927 /// let listener = UnixListener::bind("/path/to/the/socket")?;
928 /// listener.set_nonblocking(true).expect("Couldn't set non blocking");
932 #[stable(feature = "unix_socket", since = "1.10.0")]
933 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
934 self.0.set_nonblocking(nonblocking)
937 /// Returns the value of the `SO_ERROR` option.
942 /// use std::os::unix::net::UnixListener;
944 /// fn main() -> std::io::Result<()> {
945 /// let listener = UnixListener::bind("/tmp/sock")?;
947 /// if let Ok(Some(err)) = listener.take_error() {
948 /// println!("Got error: {:?}", err);
954 /// # Platform specific
955 /// On Redox this always returns `None`.
956 #[stable(feature = "unix_socket", since = "1.10.0")]
957 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
961 /// Returns an iterator over incoming connections.
963 /// The iterator will never return [`None`] and will also not yield the
964 /// peer's [`SocketAddr`] structure.
970 /// use std::os::unix::net::{UnixStream, UnixListener};
972 /// fn handle_client(stream: UnixStream) {
976 /// fn main() -> std::io::Result<()> {
977 /// let listener = UnixListener::bind("/path/to/the/socket")?;
979 /// for stream in listener.incoming() {
982 /// thread::spawn(|| handle_client(stream));
992 #[stable(feature = "unix_socket", since = "1.10.0")]
993 pub fn incoming(&self) -> Incoming<'_> {
994 Incoming { listener: self }
998 #[stable(feature = "unix_socket", since = "1.10.0")]
999 impl AsRawFd for UnixListener {
1000 fn as_raw_fd(&self) -> RawFd {
1005 #[stable(feature = "unix_socket", since = "1.10.0")]
1006 impl FromRawFd for UnixListener {
1007 unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
1008 UnixListener(Socket::from_inner(fd))
1012 #[stable(feature = "unix_socket", since = "1.10.0")]
1013 impl IntoRawFd for UnixListener {
1014 fn into_raw_fd(self) -> RawFd {
1019 #[stable(feature = "unix_socket", since = "1.10.0")]
1020 impl<'a> IntoIterator for &'a UnixListener {
1021 type Item = io::Result<UnixStream>;
1022 type IntoIter = Incoming<'a>;
1024 fn into_iter(self) -> Incoming<'a> {
1029 /// An iterator over incoming connections to a [`UnixListener`].
1031 /// It will never return [`None`].
1036 /// use std::thread;
1037 /// use std::os::unix::net::{UnixStream, UnixListener};
1039 /// fn handle_client(stream: UnixStream) {
1043 /// fn main() -> std::io::Result<()> {
1044 /// let listener = UnixListener::bind("/path/to/the/socket")?;
1046 /// for stream in listener.incoming() {
1049 /// thread::spawn(|| handle_client(stream));
1060 #[stable(feature = "unix_socket", since = "1.10.0")]
1061 pub struct Incoming<'a> {
1062 listener: &'a UnixListener,
1065 #[stable(feature = "unix_socket", since = "1.10.0")]
1066 impl<'a> Iterator for Incoming<'a> {
1067 type Item = io::Result<UnixStream>;
1069 fn next(&mut self) -> Option<io::Result<UnixStream>> {
1070 Some(self.listener.accept().map(|s| s.0))
1073 fn size_hint(&self) -> (usize, Option<usize>) {
1078 /// A Unix datagram socket.
1083 /// use std::os::unix::net::UnixDatagram;
1085 /// fn main() -> std::io::Result<()> {
1086 /// let socket = UnixDatagram::bind("/path/to/my/socket")?;
1087 /// socket.send_to(b"hello world", "/path/to/other/socket")?;
1088 /// let mut buf = [0; 100];
1089 /// let (count, address) = socket.recv_from(&mut buf)?;
1090 /// println!("socket {:?} sent {:?}", address, &buf[..count]);
1094 #[stable(feature = "unix_socket", since = "1.10.0")]
1095 pub struct UnixDatagram(Socket);
1097 #[stable(feature = "unix_socket", since = "1.10.0")]
1098 impl fmt::Debug for UnixDatagram {
1099 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 let mut builder = fmt.debug_struct("UnixDatagram");
1101 builder.field("fd", self.0.as_inner());
1102 if let Ok(addr) = self.local_addr() {
1103 builder.field("local", &addr);
1105 if let Ok(addr) = self.peer_addr() {
1106 builder.field("peer", &addr);
1113 /// Creates a Unix datagram socket bound to the given path.
1118 /// use std::os::unix::net::UnixDatagram;
1120 /// let sock = match UnixDatagram::bind("/path/to/the/socket") {
1121 /// Ok(sock) => sock,
1123 /// println!("Couldn't bind: {:?}", e);
1128 #[stable(feature = "unix_socket", since = "1.10.0")]
1129 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
1130 fn inner(path: &Path) -> io::Result<UnixDatagram> {
1132 let socket = UnixDatagram::unbound()?;
1133 let (addr, len) = sockaddr_un(path)?;
1135 cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len as _))?;
1140 inner(path.as_ref())
1143 /// Creates a Unix Datagram socket which is not bound to any address.
1148 /// use std::os::unix::net::UnixDatagram;
1150 /// let sock = match UnixDatagram::unbound() {
1151 /// Ok(sock) => sock,
1153 /// println!("Couldn't unbound: {:?}", e);
1158 #[stable(feature = "unix_socket", since = "1.10.0")]
1159 pub fn unbound() -> io::Result<UnixDatagram> {
1160 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1161 Ok(UnixDatagram(inner))
1164 /// Creates an unnamed pair of connected sockets.
1166 /// Returns two `UnixDatagrams`s which are connected to each other.
1171 /// use std::os::unix::net::UnixDatagram;
1173 /// let (sock1, sock2) = match UnixDatagram::pair() {
1174 /// Ok((sock1, sock2)) => (sock1, sock2),
1176 /// println!("Couldn't unbound: {:?}", e);
1181 #[stable(feature = "unix_socket", since = "1.10.0")]
1182 pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
1183 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1184 Ok((UnixDatagram(i1), UnixDatagram(i2)))
1187 /// Connects the socket to the specified address.
1189 /// The [`send`] method may be used to send data to the specified address.
1190 /// [`recv`] and [`recv_from`] will only receive data from that address.
1192 /// [`send`]: UnixDatagram::send
1193 /// [`recv`]: UnixDatagram::recv
1194 /// [`recv_from`]: UnixDatagram::recv_from
1199 /// use std::os::unix::net::UnixDatagram;
1201 /// fn main() -> std::io::Result<()> {
1202 /// let sock = UnixDatagram::unbound()?;
1203 /// match sock.connect("/path/to/the/socket") {
1204 /// Ok(sock) => sock,
1206 /// println!("Couldn't connect: {:?}", e);
1213 #[stable(feature = "unix_socket", since = "1.10.0")]
1214 pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1215 fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
1217 let (addr, len) = sockaddr_un(path)?;
1219 cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len))?;
1224 inner(self, path.as_ref())
1227 /// Creates a new independently owned handle to the underlying socket.
1229 /// The returned `UnixDatagram` is a reference to the same socket that this
1230 /// object references. Both handles can be used to accept incoming
1231 /// connections and options set on one side will affect the other.
1236 /// use std::os::unix::net::UnixDatagram;
1238 /// fn main() -> std::io::Result<()> {
1239 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1240 /// let sock_copy = sock.try_clone().expect("try_clone failed");
1244 #[stable(feature = "unix_socket", since = "1.10.0")]
1245 pub fn try_clone(&self) -> io::Result<UnixDatagram> {
1246 self.0.duplicate().map(UnixDatagram)
1249 /// Returns the address of this socket.
1254 /// use std::os::unix::net::UnixDatagram;
1256 /// fn main() -> std::io::Result<()> {
1257 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1258 /// let addr = sock.local_addr().expect("Couldn't get local address");
1262 #[stable(feature = "unix_socket", since = "1.10.0")]
1263 pub fn local_addr(&self) -> io::Result<SocketAddr> {
1264 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
1267 /// Returns the address of this socket's peer.
1269 /// The [`connect`] method will connect the socket to a peer.
1271 /// [`connect`]: UnixDatagram::connect
1276 /// use std::os::unix::net::UnixDatagram;
1278 /// fn main() -> std::io::Result<()> {
1279 /// let sock = UnixDatagram::unbound()?;
1280 /// sock.connect("/path/to/the/socket")?;
1282 /// let addr = sock.peer_addr().expect("Couldn't get peer address");
1286 #[stable(feature = "unix_socket", since = "1.10.0")]
1287 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
1288 SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
1291 /// Receives data from the socket.
1293 /// On success, returns the number of bytes read and the address from
1294 /// whence the data came.
1299 /// use std::os::unix::net::UnixDatagram;
1301 /// fn main() -> std::io::Result<()> {
1302 /// let sock = UnixDatagram::unbound()?;
1303 /// let mut buf = vec![0; 10];
1304 /// let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
1305 /// println!("received {} bytes from {:?}", size, sender);
1309 #[stable(feature = "unix_socket", since = "1.10.0")]
1310 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1312 let addr = SocketAddr::new(|addr, len| unsafe {
1313 count = libc::recvfrom(
1315 buf.as_mut_ptr() as *mut _,
1323 } else if count == 0 {
1330 Ok((count as usize, addr))
1333 /// Receives data from the socket.
1335 /// On success, returns the number of bytes read.
1340 /// use std::os::unix::net::UnixDatagram;
1342 /// fn main() -> std::io::Result<()> {
1343 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1344 /// let mut buf = vec![0; 10];
1345 /// sock.recv(buf.as_mut_slice()).expect("recv function failed");
1349 #[stable(feature = "unix_socket", since = "1.10.0")]
1350 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1354 /// Sends data on the socket to the specified address.
1356 /// On success, returns the number of bytes written.
1361 /// use std::os::unix::net::UnixDatagram;
1363 /// fn main() -> std::io::Result<()> {
1364 /// let sock = UnixDatagram::unbound()?;
1365 /// sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
1369 #[stable(feature = "unix_socket", since = "1.10.0")]
1370 pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
1371 fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
1373 let (addr, len) = sockaddr_un(path)?;
1375 let count = cvt(libc::sendto(
1377 buf.as_ptr() as *const _,
1380 &addr as *const _ as *const _,
1386 inner(self, buf, path.as_ref())
1389 /// Sends data on the socket to the socket's peer.
1391 /// The peer address may be set by the `connect` method, and this method
1392 /// will return an error if the socket has not already been connected.
1394 /// On success, returns the number of bytes written.
1399 /// use std::os::unix::net::UnixDatagram;
1401 /// fn main() -> std::io::Result<()> {
1402 /// let sock = UnixDatagram::unbound()?;
1403 /// sock.connect("/some/sock").expect("Couldn't connect");
1404 /// sock.send(b"omelette au fromage").expect("send_to function failed");
1408 #[stable(feature = "unix_socket", since = "1.10.0")]
1409 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
1413 /// Sets the read timeout for the socket.
1415 /// If the provided value is [`None`], then [`recv`] and [`recv_from`] calls will
1416 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`]
1417 /// is passed to this method.
1419 /// [`recv`]: UnixDatagram::recv
1420 /// [`recv_from`]: UnixDatagram::recv_from
1425 /// use std::os::unix::net::UnixDatagram;
1426 /// use std::time::Duration;
1428 /// fn main() -> std::io::Result<()> {
1429 /// let sock = UnixDatagram::unbound()?;
1430 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1431 /// .expect("set_read_timeout function failed");
1436 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1441 /// use std::os::unix::net::UnixDatagram;
1442 /// use std::time::Duration;
1444 /// fn main() -> std::io::Result<()> {
1445 /// let socket = UnixDatagram::unbound()?;
1446 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1447 /// let err = result.unwrap_err();
1448 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1452 #[stable(feature = "unix_socket", since = "1.10.0")]
1453 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1454 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
1457 /// Sets the write timeout for the socket.
1459 /// If the provided value is [`None`], then [`send`] and [`send_to`] calls will
1460 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
1463 /// [`send`]: UnixDatagram::send
1464 /// [`send_to`]: UnixDatagram::send_to
1469 /// use std::os::unix::net::UnixDatagram;
1470 /// use std::time::Duration;
1472 /// fn main() -> std::io::Result<()> {
1473 /// let sock = UnixDatagram::unbound()?;
1474 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1475 /// .expect("set_write_timeout function failed");
1480 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1485 /// use std::os::unix::net::UnixDatagram;
1486 /// use std::time::Duration;
1488 /// fn main() -> std::io::Result<()> {
1489 /// let socket = UnixDatagram::unbound()?;
1490 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1491 /// let err = result.unwrap_err();
1492 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1496 #[stable(feature = "unix_socket", since = "1.10.0")]
1497 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1498 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
1501 /// Returns the read timeout of this socket.
1506 /// use std::os::unix::net::UnixDatagram;
1507 /// use std::time::Duration;
1509 /// fn main() -> std::io::Result<()> {
1510 /// let sock = UnixDatagram::unbound()?;
1511 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1512 /// .expect("set_read_timeout function failed");
1513 /// assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
1517 #[stable(feature = "unix_socket", since = "1.10.0")]
1518 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
1519 self.0.timeout(libc::SO_RCVTIMEO)
1522 /// Returns the write timeout of this socket.
1527 /// use std::os::unix::net::UnixDatagram;
1528 /// use std::time::Duration;
1530 /// fn main() -> std::io::Result<()> {
1531 /// let sock = UnixDatagram::unbound()?;
1532 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1533 /// .expect("set_write_timeout function failed");
1534 /// assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
1538 #[stable(feature = "unix_socket", since = "1.10.0")]
1539 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
1540 self.0.timeout(libc::SO_SNDTIMEO)
1543 /// Moves the socket into or out of nonblocking mode.
1548 /// use std::os::unix::net::UnixDatagram;
1550 /// fn main() -> std::io::Result<()> {
1551 /// let sock = UnixDatagram::unbound()?;
1552 /// sock.set_nonblocking(true).expect("set_nonblocking function failed");
1556 #[stable(feature = "unix_socket", since = "1.10.0")]
1557 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1558 self.0.set_nonblocking(nonblocking)
1561 /// Returns the value of the `SO_ERROR` option.
1566 /// use std::os::unix::net::UnixDatagram;
1568 /// fn main() -> std::io::Result<()> {
1569 /// let sock = UnixDatagram::unbound()?;
1570 /// if let Ok(Some(err)) = sock.take_error() {
1571 /// println!("Got error: {:?}", err);
1576 #[stable(feature = "unix_socket", since = "1.10.0")]
1577 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1581 /// Shut down the read, write, or both halves of this connection.
1583 /// This function will cause all pending and future I/O calls on the
1584 /// specified portions to immediately return with an appropriate value
1585 /// (see the documentation of [`Shutdown`]).
1588 /// use std::os::unix::net::UnixDatagram;
1589 /// use std::net::Shutdown;
1591 /// fn main() -> std::io::Result<()> {
1592 /// let sock = UnixDatagram::unbound()?;
1593 /// sock.shutdown(Shutdown::Both).expect("shutdown function failed");
1597 #[stable(feature = "unix_socket", since = "1.10.0")]
1598 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
1599 self.0.shutdown(how)
1603 #[stable(feature = "unix_socket", since = "1.10.0")]
1604 impl AsRawFd for UnixDatagram {
1605 fn as_raw_fd(&self) -> RawFd {
1610 #[stable(feature = "unix_socket", since = "1.10.0")]
1611 impl FromRawFd for UnixDatagram {
1612 unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
1613 UnixDatagram(Socket::from_inner(fd))
1617 #[stable(feature = "unix_socket", since = "1.10.0")]
1618 impl IntoRawFd for UnixDatagram {
1619 fn into_raw_fd(self) -> RawFd {
1624 #[cfg(all(test, not(target_os = "emscripten")))]
1626 use crate::io::prelude::*;
1627 use crate::io::{self, ErrorKind};
1628 use crate::sys_common::io::test::tmpdir;
1630 use crate::time::Duration;
1634 macro_rules! or_panic {
1638 Err(e) => panic!("{}", e),
1646 let socket_path = dir.path().join("sock");
1647 let msg1 = b"hello";
1648 let msg2 = b"world!";
1650 let listener = or_panic!(UnixListener::bind(&socket_path));
1651 let thread = thread::spawn(move || {
1652 let mut stream = or_panic!(listener.accept()).0;
1653 let mut buf = [0; 5];
1654 or_panic!(stream.read(&mut buf));
1655 assert_eq!(&msg1[..], &buf[..]);
1656 or_panic!(stream.write_all(msg2));
1659 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1660 assert_eq!(Some(&*socket_path), stream.peer_addr().unwrap().as_pathname());
1661 or_panic!(stream.write_all(msg1));
1662 let mut buf = vec![];
1663 or_panic!(stream.read_to_end(&mut buf));
1664 assert_eq!(&msg2[..], &buf[..]);
1667 thread.join().unwrap();
1672 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1674 let len = or_panic!(s1.write_vectored(&[
1675 IoSlice::new(b"hello"),
1677 IoSlice::new(b"world!")
1679 assert_eq!(len, 12);
1681 let mut buf1 = [0; 6];
1682 let mut buf2 = [0; 7];
1683 let len = or_panic!(
1684 s2.read_vectored(&mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)],)
1686 assert_eq!(len, 12);
1687 assert_eq!(&buf1, b"hello ");
1688 assert_eq!(&buf2, b"world!\0");
1693 let msg1 = b"hello";
1694 let msg2 = b"world!";
1696 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1697 let thread = thread::spawn(move || {
1698 // s1 must be moved in or the test will hang!
1699 let mut buf = [0; 5];
1700 or_panic!(s1.read(&mut buf));
1701 assert_eq!(&msg1[..], &buf[..]);
1702 or_panic!(s1.write_all(msg2));
1705 or_panic!(s2.write_all(msg1));
1706 let mut buf = vec![];
1707 or_panic!(s2.read_to_end(&mut buf));
1708 assert_eq!(&msg2[..], &buf[..]);
1711 thread.join().unwrap();
1717 let socket_path = dir.path().join("sock");
1718 let msg1 = b"hello";
1719 let msg2 = b"world";
1721 let listener = or_panic!(UnixListener::bind(&socket_path));
1722 let thread = thread::spawn(move || {
1723 let mut stream = or_panic!(listener.accept()).0;
1724 or_panic!(stream.write_all(msg1));
1725 or_panic!(stream.write_all(msg2));
1728 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1729 let mut stream2 = or_panic!(stream.try_clone());
1731 let mut buf = [0; 5];
1732 or_panic!(stream.read(&mut buf));
1733 assert_eq!(&msg1[..], &buf[..]);
1734 or_panic!(stream2.read(&mut buf));
1735 assert_eq!(&msg2[..], &buf[..]);
1737 thread.join().unwrap();
1743 let socket_path = dir.path().join("sock");
1745 let listener = or_panic!(UnixListener::bind(&socket_path));
1746 let thread = thread::spawn(move || {
1747 for stream in listener.incoming().take(2) {
1748 let mut stream = or_panic!(stream);
1750 or_panic!(stream.read(&mut buf));
1755 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1756 or_panic!(stream.write_all(&[0]));
1759 thread.join().unwrap();
1765 let socket_path = dir.path().join(
1766 "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
1767 sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf",
1769 match UnixStream::connect(&socket_path) {
1770 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1771 Err(e) => panic!("unexpected error {}", e),
1772 Ok(_) => panic!("unexpected success"),
1775 match UnixListener::bind(&socket_path) {
1776 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1777 Err(e) => panic!("unexpected error {}", e),
1778 Ok(_) => panic!("unexpected success"),
1781 match UnixDatagram::bind(&socket_path) {
1782 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1783 Err(e) => panic!("unexpected error {}", e),
1784 Ok(_) => panic!("unexpected success"),
1791 let socket_path = dir.path().join("sock");
1793 let _listener = or_panic!(UnixListener::bind(&socket_path));
1795 let stream = or_panic!(UnixStream::connect(&socket_path));
1796 let dur = Duration::new(15410, 0);
1798 assert_eq!(None, or_panic!(stream.read_timeout()));
1800 or_panic!(stream.set_read_timeout(Some(dur)));
1801 assert_eq!(Some(dur), or_panic!(stream.read_timeout()));
1803 assert_eq!(None, or_panic!(stream.write_timeout()));
1805 or_panic!(stream.set_write_timeout(Some(dur)));
1806 assert_eq!(Some(dur), or_panic!(stream.write_timeout()));
1808 or_panic!(stream.set_read_timeout(None));
1809 assert_eq!(None, or_panic!(stream.read_timeout()));
1811 or_panic!(stream.set_write_timeout(None));
1812 assert_eq!(None, or_panic!(stream.write_timeout()));
1816 fn test_read_timeout() {
1818 let socket_path = dir.path().join("sock");
1820 let _listener = or_panic!(UnixListener::bind(&socket_path));
1822 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1823 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1825 let mut buf = [0; 10];
1826 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1828 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1829 "unexpected_error: {:?}",
1835 fn test_read_with_timeout() {
1837 let socket_path = dir.path().join("sock");
1839 let listener = or_panic!(UnixListener::bind(&socket_path));
1841 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1842 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1844 let mut other_end = or_panic!(listener.accept()).0;
1845 or_panic!(other_end.write_all(b"hello world"));
1847 let mut buf = [0; 11];
1848 or_panic!(stream.read(&mut buf));
1849 assert_eq!(b"hello world", &buf[..]);
1851 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1853 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1854 "unexpected_error: {:?}",
1859 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1860 // when passed zero Durations
1862 fn test_unix_stream_timeout_zero_duration() {
1864 let socket_path = dir.path().join("sock");
1866 let listener = or_panic!(UnixListener::bind(&socket_path));
1867 let stream = or_panic!(UnixStream::connect(&socket_path));
1869 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1870 let err = result.unwrap_err();
1871 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1873 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1874 let err = result.unwrap_err();
1875 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1881 fn test_unix_datagram() {
1883 let path1 = dir.path().join("sock1");
1884 let path2 = dir.path().join("sock2");
1886 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1887 let sock2 = or_panic!(UnixDatagram::bind(&path2));
1889 let msg = b"hello world";
1890 or_panic!(sock1.send_to(msg, &path2));
1891 let mut buf = [0; 11];
1892 or_panic!(sock2.recv_from(&mut buf));
1893 assert_eq!(msg, &buf[..]);
1897 fn test_unnamed_unix_datagram() {
1899 let path1 = dir.path().join("sock1");
1901 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1902 let sock2 = or_panic!(UnixDatagram::unbound());
1904 let msg = b"hello world";
1905 or_panic!(sock2.send_to(msg, &path1));
1906 let mut buf = [0; 11];
1907 let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
1908 assert_eq!(usize, 11);
1909 assert!(addr.is_unnamed());
1910 assert_eq!(msg, &buf[..]);
1914 fn test_connect_unix_datagram() {
1916 let path1 = dir.path().join("sock1");
1917 let path2 = dir.path().join("sock2");
1919 let bsock1 = or_panic!(UnixDatagram::bind(&path1));
1920 let bsock2 = or_panic!(UnixDatagram::bind(&path2));
1921 let sock = or_panic!(UnixDatagram::unbound());
1922 or_panic!(sock.connect(&path1));
1925 let msg = b"hello there";
1926 or_panic!(sock.send(msg));
1927 let mut buf = [0; 11];
1928 let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
1929 assert_eq!(usize, 11);
1930 assert!(addr.is_unnamed());
1931 assert_eq!(msg, &buf[..]);
1933 // Changing default socket works too
1934 or_panic!(sock.connect(&path2));
1935 or_panic!(sock.send(msg));
1936 or_panic!(bsock2.recv_from(&mut buf));
1940 fn test_unix_datagram_recv() {
1942 let path1 = dir.path().join("sock1");
1944 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1945 let sock2 = or_panic!(UnixDatagram::unbound());
1946 or_panic!(sock2.connect(&path1));
1948 let msg = b"hello world";
1949 or_panic!(sock2.send(msg));
1950 let mut buf = [0; 11];
1951 let size = or_panic!(sock1.recv(&mut buf));
1952 assert_eq!(size, 11);
1953 assert_eq!(msg, &buf[..]);
1957 fn datagram_pair() {
1958 let msg1 = b"hello";
1959 let msg2 = b"world!";
1961 let (s1, s2) = or_panic!(UnixDatagram::pair());
1962 let thread = thread::spawn(move || {
1963 // s1 must be moved in or the test will hang!
1964 let mut buf = [0; 5];
1965 or_panic!(s1.recv(&mut buf));
1966 assert_eq!(&msg1[..], &buf[..]);
1967 or_panic!(s1.send(msg2));
1970 or_panic!(s2.send(msg1));
1971 let mut buf = [0; 6];
1972 or_panic!(s2.recv(&mut buf));
1973 assert_eq!(&msg2[..], &buf[..]);
1976 thread.join().unwrap();
1979 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1980 // when passed zero Durations
1982 fn test_unix_datagram_timeout_zero_duration() {
1984 let path = dir.path().join("sock");
1986 let datagram = or_panic!(UnixDatagram::bind(&path));
1988 let result = datagram.set_write_timeout(Some(Duration::new(0, 0)));
1989 let err = result.unwrap_err();
1990 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1992 let result = datagram.set_read_timeout(Some(Duration::new(0, 0)));
1993 let err = result.unwrap_err();
1994 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1998 fn abstract_namespace_not_allowed() {
1999 assert!(UnixStream::connect("\0asdf").is_err());