1 #![stable(feature = "unix_socket", since = "1.10.0")]
3 //! Unix-specific networking functionality
8 // FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
12 pub type socklen_t = u32;
15 pub struct sockaddr_un;
19 use crate::ffi::OsStr;
21 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
23 use crate::net::{self, Shutdown};
24 use crate::os::unix::ffi::OsStrExt;
25 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
26 use crate::path::Path;
27 use crate::sys::net::Socket;
28 use crate::sys::{self, cvt};
29 use crate::sys_common::{self, AsInner, FromInner, IntoInner};
30 use crate::time::Duration;
34 target_os = "android",
35 target_os = "dragonfly",
36 target_os = "freebsd",
37 target_os = "openbsd",
41 use libc::MSG_NOSIGNAL;
44 target_os = "android",
45 target_os = "dragonfly",
46 target_os = "freebsd",
47 target_os = "openbsd",
51 const MSG_NOSIGNAL: libc::c_int = 0x0;
53 fn sun_path_offset(addr: &libc::sockaddr_un) -> usize {
54 // Work with an actual instance of the type since using a null pointer is UB
55 let base = addr as *const _ as usize;
56 let path = &addr.sun_path as *const _ as usize;
60 unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
61 let mut addr: libc::sockaddr_un = mem::zeroed();
62 addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
64 let bytes = path.as_os_str().as_bytes();
66 if bytes.contains(&0) {
67 return Err(io::Error::new(
68 io::ErrorKind::InvalidInput,
69 "paths may not contain interior null bytes",
73 if bytes.len() >= addr.sun_path.len() {
74 return Err(io::Error::new(
75 io::ErrorKind::InvalidInput,
76 "path must be shorter than SUN_LEN",
79 for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
80 *dst = *src as libc::c_char;
82 // null byte for pathname addresses is already there because we zeroed the
85 let mut len = sun_path_offset(&addr) + bytes.len();
90 Ok((addr, len as libc::socklen_t))
93 enum AddressKind<'a> {
99 /// An address associated with a Unix socket.
104 /// use std::os::unix::net::UnixListener;
106 /// let socket = match UnixListener::bind("/tmp/sock") {
107 /// Ok(sock) => sock,
109 /// println!("Couldn't bind: {:?}", e);
113 /// let addr = socket.local_addr().expect("Couldn't get local address");
116 #[stable(feature = "unix_socket", since = "1.10.0")]
117 pub struct SocketAddr {
118 addr: libc::sockaddr_un,
119 len: libc::socklen_t,
123 fn new<F>(f: F) -> io::Result<SocketAddr>
125 F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int,
128 let mut addr: libc::sockaddr_un = mem::zeroed();
129 let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
130 cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
131 SocketAddr::from_parts(addr, len)
135 fn from_parts(addr: libc::sockaddr_un, mut len: libc::socklen_t) -> io::Result<SocketAddr> {
137 // When there is a datagram from unnamed unix socket
138 // linux returns zero bytes of address
139 len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address
140 } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
141 return Err(io::Error::new(
142 io::ErrorKind::InvalidInput,
143 "file descriptor did not correspond to a Unix socket",
147 Ok(SocketAddr { addr, len })
150 /// Returns `true` if the address is unnamed.
157 /// use std::os::unix::net::UnixListener;
159 /// fn main() -> std::io::Result<()> {
160 /// let socket = UnixListener::bind("/tmp/sock")?;
161 /// let addr = socket.local_addr().expect("Couldn't get local address");
162 /// assert_eq!(addr.is_unnamed(), false);
167 /// An unnamed address:
170 /// use std::os::unix::net::UnixDatagram;
172 /// fn main() -> std::io::Result<()> {
173 /// let socket = UnixDatagram::unbound()?;
174 /// let addr = socket.local_addr().expect("Couldn't get local address");
175 /// assert_eq!(addr.is_unnamed(), true);
179 #[stable(feature = "unix_socket", since = "1.10.0")]
180 pub fn is_unnamed(&self) -> bool {
181 if let AddressKind::Unnamed = self.address() { true } else { false }
184 /// Returns the contents of this address if it is a `pathname` address.
191 /// use std::os::unix::net::UnixListener;
192 /// use std::path::Path;
194 /// fn main() -> std::io::Result<()> {
195 /// let socket = UnixListener::bind("/tmp/sock")?;
196 /// let addr = socket.local_addr().expect("Couldn't get local address");
197 /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
202 /// Without a pathname:
205 /// use std::os::unix::net::UnixDatagram;
207 /// fn main() -> std::io::Result<()> {
208 /// let socket = UnixDatagram::unbound()?;
209 /// let addr = socket.local_addr().expect("Couldn't get local address");
210 /// assert_eq!(addr.as_pathname(), None);
214 #[stable(feature = "unix_socket", since = "1.10.0")]
215 pub fn as_pathname(&self) -> Option<&Path> {
216 if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
219 fn address(&self) -> AddressKind<'_> {
220 let len = self.len as usize - sun_path_offset(&self.addr);
221 let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
223 // macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
225 || (cfg!(not(any(target_os = "linux", target_os = "android")))
226 && self.addr.sun_path[0] == 0)
229 } else if self.addr.sun_path[0] == 0 {
230 AddressKind::Abstract(&path[1..len])
232 AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
237 #[stable(feature = "unix_socket", since = "1.10.0")]
238 impl fmt::Debug for SocketAddr {
239 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
240 match self.address() {
241 AddressKind::Unnamed => write!(fmt, "(unnamed)"),
242 AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
243 AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
248 struct AsciiEscaped<'a>(&'a [u8]);
250 impl<'a> fmt::Display for AsciiEscaped<'a> {
251 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
253 for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
254 write!(fmt, "{}", byte as char)?;
260 /// A Unix stream socket.
265 /// use std::os::unix::net::UnixStream;
266 /// use std::io::prelude::*;
268 /// fn main() -> std::io::Result<()> {
269 /// let mut stream = UnixStream::connect("/path/to/my/socket")?;
270 /// stream.write_all(b"hello world")?;
271 /// let mut response = String::new();
272 /// stream.read_to_string(&mut response)?;
273 /// println!("{}", response);
277 #[stable(feature = "unix_socket", since = "1.10.0")]
278 pub struct UnixStream(Socket);
280 #[stable(feature = "unix_socket", since = "1.10.0")]
281 impl fmt::Debug for UnixStream {
282 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
283 let mut builder = fmt.debug_struct("UnixStream");
284 builder.field("fd", self.0.as_inner());
285 if let Ok(addr) = self.local_addr() {
286 builder.field("local", &addr);
288 if let Ok(addr) = self.peer_addr() {
289 builder.field("peer", &addr);
296 /// Connects to the socket named by `path`.
301 /// use std::os::unix::net::UnixStream;
303 /// let socket = match UnixStream::connect("/tmp/sock") {
304 /// Ok(sock) => sock,
306 /// println!("Couldn't connect: {:?}", e);
311 #[stable(feature = "unix_socket", since = "1.10.0")]
312 pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
313 fn inner(path: &Path) -> io::Result<UnixStream> {
315 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
316 let (addr, len) = sockaddr_un(path)?;
318 cvt(libc::connect(*inner.as_inner(), &addr as *const _ as *const _, len))?;
319 Ok(UnixStream(inner))
325 /// Creates an unnamed pair of connected sockets.
327 /// Returns two `UnixStream`s which are connected to each other.
332 /// use std::os::unix::net::UnixStream;
334 /// let (sock1, sock2) = match UnixStream::pair() {
335 /// Ok((sock1, sock2)) => (sock1, sock2),
337 /// println!("Couldn't create a pair of sockets: {:?}", e);
342 #[stable(feature = "unix_socket", since = "1.10.0")]
343 pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
344 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM)?;
345 Ok((UnixStream(i1), UnixStream(i2)))
348 /// Creates a new independently owned handle to the underlying socket.
350 /// The returned `UnixStream` is a reference to the same stream that this
351 /// object references. Both handles will read and write the same stream of
352 /// data, and options set on one stream will be propagated to the other
358 /// use std::os::unix::net::UnixStream;
360 /// fn main() -> std::io::Result<()> {
361 /// let socket = UnixStream::connect("/tmp/sock")?;
362 /// let sock_copy = socket.try_clone().expect("Couldn't clone socket");
366 #[stable(feature = "unix_socket", since = "1.10.0")]
367 pub fn try_clone(&self) -> io::Result<UnixStream> {
368 self.0.duplicate().map(UnixStream)
371 /// Returns the socket address of the local half of this connection.
376 /// use std::os::unix::net::UnixStream;
378 /// fn main() -> std::io::Result<()> {
379 /// let socket = UnixStream::connect("/tmp/sock")?;
380 /// let addr = socket.local_addr().expect("Couldn't get local address");
384 #[stable(feature = "unix_socket", since = "1.10.0")]
385 pub fn local_addr(&self) -> io::Result<SocketAddr> {
386 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
389 /// Returns the socket address of the remote half of this connection.
394 /// use std::os::unix::net::UnixStream;
396 /// fn main() -> std::io::Result<()> {
397 /// let socket = UnixStream::connect("/tmp/sock")?;
398 /// let addr = socket.peer_addr().expect("Couldn't get peer address");
402 #[stable(feature = "unix_socket", since = "1.10.0")]
403 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
404 SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
407 /// Sets the read timeout for the socket.
409 /// If the provided value is [`None`], then [`read`] calls will block
410 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
413 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
414 /// [`Err`]: ../../../../std/result/enum.Result.html#variant.Err
415 /// [`read`]: ../../../../std/io/trait.Read.html#tymethod.read
416 /// [`Duration`]: ../../../../std/time/struct.Duration.html
421 /// use std::os::unix::net::UnixStream;
422 /// use std::time::Duration;
424 /// fn main() -> std::io::Result<()> {
425 /// let socket = UnixStream::connect("/tmp/sock")?;
426 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
431 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
436 /// use std::os::unix::net::UnixStream;
437 /// use std::time::Duration;
439 /// fn main() -> std::io::Result<()> {
440 /// let socket = UnixStream::connect("/tmp/sock")?;
441 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
442 /// let err = result.unwrap_err();
443 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
447 #[stable(feature = "unix_socket", since = "1.10.0")]
448 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
449 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
452 /// Sets the write timeout for the socket.
454 /// If the provided value is [`None`], then [`write`] calls will block
455 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
456 /// passed to this method.
458 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
459 /// [`Err`]: ../../../../std/result/enum.Result.html#variant.Err
460 /// [`write`]: ../../../../std/io/trait.Write.html#tymethod.write
461 /// [`Duration`]: ../../../../std/time/struct.Duration.html
466 /// use std::os::unix::net::UnixStream;
467 /// use std::time::Duration;
469 /// fn main() -> std::io::Result<()> {
470 /// let socket = UnixStream::connect("/tmp/sock")?;
471 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
472 /// .expect("Couldn't set write timeout");
477 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
482 /// use std::net::UdpSocket;
483 /// use std::time::Duration;
485 /// fn main() -> std::io::Result<()> {
486 /// let socket = UdpSocket::bind("127.0.0.1:34254")?;
487 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
488 /// let err = result.unwrap_err();
489 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
493 #[stable(feature = "unix_socket", since = "1.10.0")]
494 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
495 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
498 /// Returns the read timeout of this socket.
503 /// use std::os::unix::net::UnixStream;
504 /// use std::time::Duration;
506 /// fn main() -> std::io::Result<()> {
507 /// let socket = UnixStream::connect("/tmp/sock")?;
508 /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
509 /// assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
513 #[stable(feature = "unix_socket", since = "1.10.0")]
514 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
515 self.0.timeout(libc::SO_RCVTIMEO)
518 /// Returns the write timeout of this socket.
523 /// use std::os::unix::net::UnixStream;
524 /// use std::time::Duration;
526 /// fn main() -> std::io::Result<()> {
527 /// let socket = UnixStream::connect("/tmp/sock")?;
528 /// socket.set_write_timeout(Some(Duration::new(1, 0)))
529 /// .expect("Couldn't set write timeout");
530 /// assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
534 #[stable(feature = "unix_socket", since = "1.10.0")]
535 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
536 self.0.timeout(libc::SO_SNDTIMEO)
539 /// Moves the socket into or out of nonblocking mode.
544 /// use std::os::unix::net::UnixStream;
546 /// fn main() -> std::io::Result<()> {
547 /// let socket = UnixStream::connect("/tmp/sock")?;
548 /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
552 #[stable(feature = "unix_socket", since = "1.10.0")]
553 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
554 self.0.set_nonblocking(nonblocking)
557 /// Returns the value of the `SO_ERROR` option.
562 /// use std::os::unix::net::UnixStream;
564 /// fn main() -> std::io::Result<()> {
565 /// let socket = UnixStream::connect("/tmp/sock")?;
566 /// if let Ok(Some(err)) = socket.take_error() {
567 /// println!("Got error: {:?}", err);
573 /// # Platform specific
574 /// On Redox this always returns `None`.
575 #[stable(feature = "unix_socket", since = "1.10.0")]
576 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
580 /// Shuts down the read, write, or both halves of this connection.
582 /// This function will cause all pending and future I/O calls on the
583 /// specified portions to immediately return with an appropriate value
584 /// (see the documentation of [`Shutdown`]).
586 /// [`Shutdown`]: ../../../../std/net/enum.Shutdown.html
591 /// use std::os::unix::net::UnixStream;
592 /// use std::net::Shutdown;
594 /// fn main() -> std::io::Result<()> {
595 /// let socket = UnixStream::connect("/tmp/sock")?;
596 /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
600 #[stable(feature = "unix_socket", since = "1.10.0")]
601 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
606 #[stable(feature = "unix_socket", since = "1.10.0")]
607 impl io::Read for UnixStream {
608 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
609 io::Read::read(&mut &*self, buf)
612 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
613 io::Read::read_vectored(&mut &*self, bufs)
617 unsafe fn initializer(&self) -> Initializer {
622 #[stable(feature = "unix_socket", since = "1.10.0")]
623 impl<'a> io::Read for &'a UnixStream {
624 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
628 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
629 self.0.read_vectored(bufs)
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)
648 fn flush(&mut self) -> io::Result<()> {
649 io::Write::flush(&mut &*self)
653 #[stable(feature = "unix_socket", since = "1.10.0")]
654 impl<'a> io::Write for &'a UnixStream {
655 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
659 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
660 self.0.write_vectored(bufs)
663 fn flush(&mut self) -> io::Result<()> {
668 #[stable(feature = "unix_socket", since = "1.10.0")]
669 impl AsRawFd for UnixStream {
670 fn as_raw_fd(&self) -> RawFd {
675 #[stable(feature = "unix_socket", since = "1.10.0")]
676 impl FromRawFd for UnixStream {
677 unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
678 UnixStream(Socket::from_inner(fd))
682 #[stable(feature = "unix_socket", since = "1.10.0")]
683 impl IntoRawFd for UnixStream {
684 fn into_raw_fd(self) -> RawFd {
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl AsRawFd for net::TcpStream {
691 fn as_raw_fd(&self) -> RawFd {
692 *self.as_inner().socket().as_inner()
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl AsRawFd for net::TcpListener {
698 fn as_raw_fd(&self) -> RawFd {
699 *self.as_inner().socket().as_inner()
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl AsRawFd for net::UdpSocket {
705 fn as_raw_fd(&self) -> RawFd {
706 *self.as_inner().socket().as_inner()
710 #[stable(feature = "from_raw_os", since = "1.1.0")]
711 impl FromRawFd for net::TcpStream {
712 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
713 let socket = sys::net::Socket::from_inner(fd);
714 net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
718 #[stable(feature = "from_raw_os", since = "1.1.0")]
719 impl FromRawFd for net::TcpListener {
720 unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
721 let socket = sys::net::Socket::from_inner(fd);
722 net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
726 #[stable(feature = "from_raw_os", since = "1.1.0")]
727 impl FromRawFd for net::UdpSocket {
728 unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
729 let socket = sys::net::Socket::from_inner(fd);
730 net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
734 #[stable(feature = "into_raw_os", since = "1.4.0")]
735 impl IntoRawFd for net::TcpStream {
736 fn into_raw_fd(self) -> RawFd {
737 self.into_inner().into_socket().into_inner()
740 #[stable(feature = "into_raw_os", since = "1.4.0")]
741 impl IntoRawFd for net::TcpListener {
742 fn into_raw_fd(self) -> RawFd {
743 self.into_inner().into_socket().into_inner()
746 #[stable(feature = "into_raw_os", since = "1.4.0")]
747 impl IntoRawFd for net::UdpSocket {
748 fn into_raw_fd(self) -> RawFd {
749 self.into_inner().into_socket().into_inner()
753 /// A structure representing a Unix domain socket server.
759 /// use std::os::unix::net::{UnixStream, UnixListener};
761 /// fn handle_client(stream: UnixStream) {
765 /// fn main() -> std::io::Result<()> {
766 /// let listener = UnixListener::bind("/path/to/the/socket")?;
768 /// // accept connections and process them, spawning a new thread for each one
769 /// for stream in listener.incoming() {
772 /// /* connection succeeded */
773 /// thread::spawn(|| handle_client(stream));
776 /// /* connection failed */
784 #[stable(feature = "unix_socket", since = "1.10.0")]
785 pub struct UnixListener(Socket);
787 #[stable(feature = "unix_socket", since = "1.10.0")]
788 impl fmt::Debug for UnixListener {
789 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
790 let mut builder = fmt.debug_struct("UnixListener");
791 builder.field("fd", self.0.as_inner());
792 if let Ok(addr) = self.local_addr() {
793 builder.field("local", &addr);
800 /// Creates a new `UnixListener` bound to the specified socket.
805 /// use std::os::unix::net::UnixListener;
807 /// let listener = match UnixListener::bind("/path/to/the/socket") {
808 /// Ok(sock) => sock,
810 /// println!("Couldn't connect: {:?}", e);
815 #[stable(feature = "unix_socket", since = "1.10.0")]
816 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
817 fn inner(path: &Path) -> io::Result<UnixListener> {
819 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
820 let (addr, len) = sockaddr_un(path)?;
822 cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len as _))?;
823 cvt(libc::listen(*inner.as_inner(), 128))?;
825 Ok(UnixListener(inner))
831 /// Accepts a new incoming connection to this listener.
833 /// This function will block the calling thread until a new Unix connection
834 /// is established. When established, the corresponding [`UnixStream`] and
835 /// the remote peer's address will be returned.
837 /// [`UnixStream`]: ../../../../std/os/unix/net/struct.UnixStream.html
842 /// use std::os::unix::net::UnixListener;
844 /// fn main() -> std::io::Result<()> {
845 /// let listener = UnixListener::bind("/path/to/the/socket")?;
847 /// match listener.accept() {
848 /// Ok((socket, addr)) => println!("Got a client: {:?}", addr),
849 /// Err(e) => println!("accept function failed: {:?}", e),
854 #[stable(feature = "unix_socket", since = "1.10.0")]
855 pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
856 let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
857 let mut len = mem::size_of_val(&storage) as libc::socklen_t;
858 let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
859 let addr = SocketAddr::from_parts(storage, len)?;
860 Ok((UnixStream(sock), addr))
863 /// Creates a new independently owned handle to the underlying socket.
865 /// The returned `UnixListener` is a reference to the same socket that this
866 /// object references. Both handles can be used to accept incoming
867 /// connections and options set on one listener will affect the other.
872 /// use std::os::unix::net::UnixListener;
874 /// fn main() -> std::io::Result<()> {
875 /// let listener = UnixListener::bind("/path/to/the/socket")?;
876 /// let listener_copy = listener.try_clone().expect("try_clone failed");
880 #[stable(feature = "unix_socket", since = "1.10.0")]
881 pub fn try_clone(&self) -> io::Result<UnixListener> {
882 self.0.duplicate().map(UnixListener)
885 /// Returns the local socket address of this listener.
890 /// use std::os::unix::net::UnixListener;
892 /// fn main() -> std::io::Result<()> {
893 /// let listener = UnixListener::bind("/path/to/the/socket")?;
894 /// let addr = listener.local_addr().expect("Couldn't get local address");
898 #[stable(feature = "unix_socket", since = "1.10.0")]
899 pub fn local_addr(&self) -> io::Result<SocketAddr> {
900 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
903 /// Moves the socket into or out of nonblocking mode.
905 /// This will result in the `accept` operation becoming nonblocking,
906 /// i.e., immediately returning from their calls. If the IO operation is
907 /// successful, `Ok` is returned and no further action is required. If the
908 /// IO operation could not be completed and needs to be retried, an error
909 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
914 /// use std::os::unix::net::UnixListener;
916 /// fn main() -> std::io::Result<()> {
917 /// let listener = UnixListener::bind("/path/to/the/socket")?;
918 /// listener.set_nonblocking(true).expect("Couldn't set non blocking");
923 /// [`io::ErrorKind::WouldBlock`]: ../../../io/enum.ErrorKind.html#variant.WouldBlock
924 #[stable(feature = "unix_socket", since = "1.10.0")]
925 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
926 self.0.set_nonblocking(nonblocking)
929 /// Returns the value of the `SO_ERROR` option.
934 /// use std::os::unix::net::UnixListener;
936 /// fn main() -> std::io::Result<()> {
937 /// let listener = UnixListener::bind("/tmp/sock")?;
939 /// if let Ok(Some(err)) = listener.take_error() {
940 /// println!("Got error: {:?}", err);
946 /// # Platform specific
947 /// On Redox this always returns `None`.
948 #[stable(feature = "unix_socket", since = "1.10.0")]
949 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
953 /// Returns an iterator over incoming connections.
955 /// The iterator will never return [`None`] and will also not yield the
956 /// peer's [`SocketAddr`] structure.
958 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
959 /// [`SocketAddr`]: struct.SocketAddr.html
965 /// use std::os::unix::net::{UnixStream, UnixListener};
967 /// fn handle_client(stream: UnixStream) {
971 /// fn main() -> std::io::Result<()> {
972 /// let listener = UnixListener::bind("/path/to/the/socket")?;
974 /// for stream in listener.incoming() {
977 /// thread::spawn(|| handle_client(stream));
987 #[stable(feature = "unix_socket", since = "1.10.0")]
988 pub fn incoming(&self) -> Incoming<'_> {
989 Incoming { listener: self }
993 #[stable(feature = "unix_socket", since = "1.10.0")]
994 impl AsRawFd for UnixListener {
995 fn as_raw_fd(&self) -> RawFd {
1000 #[stable(feature = "unix_socket", since = "1.10.0")]
1001 impl FromRawFd for UnixListener {
1002 unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
1003 UnixListener(Socket::from_inner(fd))
1007 #[stable(feature = "unix_socket", since = "1.10.0")]
1008 impl IntoRawFd for UnixListener {
1009 fn into_raw_fd(self) -> RawFd {
1014 #[stable(feature = "unix_socket", since = "1.10.0")]
1015 impl<'a> IntoIterator for &'a UnixListener {
1016 type Item = io::Result<UnixStream>;
1017 type IntoIter = Incoming<'a>;
1019 fn into_iter(self) -> Incoming<'a> {
1024 /// An iterator over incoming connections to a [`UnixListener`].
1026 /// It will never return [`None`].
1028 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
1029 /// [`UnixListener`]: struct.UnixListener.html
1034 /// use std::thread;
1035 /// use std::os::unix::net::{UnixStream, UnixListener};
1037 /// fn handle_client(stream: UnixStream) {
1041 /// fn main() -> std::io::Result<()> {
1042 /// let listener = UnixListener::bind("/path/to/the/socket")?;
1044 /// for stream in listener.incoming() {
1047 /// thread::spawn(|| handle_client(stream));
1058 #[stable(feature = "unix_socket", since = "1.10.0")]
1059 pub struct Incoming<'a> {
1060 listener: &'a UnixListener,
1063 #[stable(feature = "unix_socket", since = "1.10.0")]
1064 impl<'a> Iterator for Incoming<'a> {
1065 type Item = io::Result<UnixStream>;
1067 fn next(&mut self) -> Option<io::Result<UnixStream>> {
1068 Some(self.listener.accept().map(|s| s.0))
1071 fn size_hint(&self) -> (usize, Option<usize>) {
1072 (usize::max_value(), None)
1076 /// A Unix datagram socket.
1081 /// use std::os::unix::net::UnixDatagram;
1083 /// fn main() -> std::io::Result<()> {
1084 /// let socket = UnixDatagram::bind("/path/to/my/socket")?;
1085 /// socket.send_to(b"hello world", "/path/to/other/socket")?;
1086 /// let mut buf = [0; 100];
1087 /// let (count, address) = socket.recv_from(&mut buf)?;
1088 /// println!("socket {:?} sent {:?}", address, &buf[..count]);
1092 #[stable(feature = "unix_socket", since = "1.10.0")]
1093 pub struct UnixDatagram(Socket);
1095 #[stable(feature = "unix_socket", since = "1.10.0")]
1096 impl fmt::Debug for UnixDatagram {
1097 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1098 let mut builder = fmt.debug_struct("UnixDatagram");
1099 builder.field("fd", self.0.as_inner());
1100 if let Ok(addr) = self.local_addr() {
1101 builder.field("local", &addr);
1103 if let Ok(addr) = self.peer_addr() {
1104 builder.field("peer", &addr);
1111 /// Creates a Unix datagram socket bound to the given path.
1116 /// use std::os::unix::net::UnixDatagram;
1118 /// let sock = match UnixDatagram::bind("/path/to/the/socket") {
1119 /// Ok(sock) => sock,
1121 /// println!("Couldn't bind: {:?}", e);
1126 #[stable(feature = "unix_socket", since = "1.10.0")]
1127 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
1128 fn inner(path: &Path) -> io::Result<UnixDatagram> {
1130 let socket = UnixDatagram::unbound()?;
1131 let (addr, len) = sockaddr_un(path)?;
1133 cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len as _))?;
1138 inner(path.as_ref())
1141 /// Creates a Unix Datagram socket which is not bound to any address.
1146 /// use std::os::unix::net::UnixDatagram;
1148 /// let sock = match UnixDatagram::unbound() {
1149 /// Ok(sock) => sock,
1151 /// println!("Couldn't unbound: {:?}", e);
1156 #[stable(feature = "unix_socket", since = "1.10.0")]
1157 pub fn unbound() -> io::Result<UnixDatagram> {
1158 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1159 Ok(UnixDatagram(inner))
1162 /// Creates an unnamed pair of connected sockets.
1164 /// Returns two `UnixDatagrams`s which are connected to each other.
1169 /// use std::os::unix::net::UnixDatagram;
1171 /// let (sock1, sock2) = match UnixDatagram::pair() {
1172 /// Ok((sock1, sock2)) => (sock1, sock2),
1174 /// println!("Couldn't unbound: {:?}", e);
1179 #[stable(feature = "unix_socket", since = "1.10.0")]
1180 pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
1181 let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
1182 Ok((UnixDatagram(i1), UnixDatagram(i2)))
1185 /// Connects the socket to the specified address.
1187 /// The [`send`] method may be used to send data to the specified address.
1188 /// [`recv`] and [`recv_from`] will only receive data from that address.
1190 /// [`send`]: #method.send
1191 /// [`recv`]: #method.recv
1192 /// [`recv_from`]: #method.recv_from
1197 /// use std::os::unix::net::UnixDatagram;
1199 /// fn main() -> std::io::Result<()> {
1200 /// let sock = UnixDatagram::unbound()?;
1201 /// match sock.connect("/path/to/the/socket") {
1202 /// Ok(sock) => sock,
1204 /// println!("Couldn't connect: {:?}", e);
1211 #[stable(feature = "unix_socket", since = "1.10.0")]
1212 pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1213 fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
1215 let (addr, len) = sockaddr_un(path)?;
1217 cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len))?;
1222 inner(self, path.as_ref())
1225 /// Creates a new independently owned handle to the underlying socket.
1227 /// The returned `UnixDatagram` is a reference to the same socket that this
1228 /// object references. Both handles can be used to accept incoming
1229 /// connections and options set on one side will affect the other.
1234 /// use std::os::unix::net::UnixDatagram;
1236 /// fn main() -> std::io::Result<()> {
1237 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1238 /// let sock_copy = sock.try_clone().expect("try_clone failed");
1242 #[stable(feature = "unix_socket", since = "1.10.0")]
1243 pub fn try_clone(&self) -> io::Result<UnixDatagram> {
1244 self.0.duplicate().map(UnixDatagram)
1247 /// Returns the address of this socket.
1252 /// use std::os::unix::net::UnixDatagram;
1254 /// fn main() -> std::io::Result<()> {
1255 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1256 /// let addr = sock.local_addr().expect("Couldn't get local address");
1260 #[stable(feature = "unix_socket", since = "1.10.0")]
1261 pub fn local_addr(&self) -> io::Result<SocketAddr> {
1262 SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
1265 /// Returns the address of this socket's peer.
1267 /// The [`connect`] method will connect the socket to a peer.
1269 /// [`connect`]: #method.connect
1274 /// use std::os::unix::net::UnixDatagram;
1276 /// fn main() -> std::io::Result<()> {
1277 /// let sock = UnixDatagram::unbound()?;
1278 /// sock.connect("/path/to/the/socket")?;
1280 /// let addr = sock.peer_addr().expect("Couldn't get peer address");
1284 #[stable(feature = "unix_socket", since = "1.10.0")]
1285 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
1286 SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
1289 /// Receives data from the socket.
1291 /// On success, returns the number of bytes read and the address from
1292 /// whence the data came.
1297 /// use std::os::unix::net::UnixDatagram;
1299 /// fn main() -> std::io::Result<()> {
1300 /// let sock = UnixDatagram::unbound()?;
1301 /// let mut buf = vec![0; 10];
1302 /// let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
1303 /// println!("received {} bytes from {:?}", size, sender);
1307 #[stable(feature = "unix_socket", since = "1.10.0")]
1308 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1310 let addr = SocketAddr::new(|addr, len| unsafe {
1311 count = libc::recvfrom(
1313 buf.as_mut_ptr() as *mut _,
1321 } else if count == 0 {
1328 Ok((count as usize, addr))
1331 /// Receives data from the socket.
1333 /// On success, returns the number of bytes read.
1338 /// use std::os::unix::net::UnixDatagram;
1340 /// fn main() -> std::io::Result<()> {
1341 /// let sock = UnixDatagram::bind("/path/to/the/socket")?;
1342 /// let mut buf = vec![0; 10];
1343 /// sock.recv(buf.as_mut_slice()).expect("recv function failed");
1347 #[stable(feature = "unix_socket", since = "1.10.0")]
1348 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1352 /// Sends data on the socket to the specified address.
1354 /// On success, returns the number of bytes written.
1359 /// use std::os::unix::net::UnixDatagram;
1361 /// fn main() -> std::io::Result<()> {
1362 /// let sock = UnixDatagram::unbound()?;
1363 /// sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
1367 #[stable(feature = "unix_socket", since = "1.10.0")]
1368 pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
1369 fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
1371 let (addr, len) = sockaddr_un(path)?;
1373 let count = cvt(libc::sendto(
1375 buf.as_ptr() as *const _,
1378 &addr as *const _ as *const _,
1384 inner(self, buf, path.as_ref())
1387 /// Sends data on the socket to the socket's peer.
1389 /// The peer address may be set by the `connect` method, and this method
1390 /// will return an error if the socket has not already been connected.
1392 /// On success, returns the number of bytes written.
1397 /// use std::os::unix::net::UnixDatagram;
1399 /// fn main() -> std::io::Result<()> {
1400 /// let sock = UnixDatagram::unbound()?;
1401 /// sock.connect("/some/sock").expect("Couldn't connect");
1402 /// sock.send(b"omelette au fromage").expect("send_to function failed");
1406 #[stable(feature = "unix_socket", since = "1.10.0")]
1407 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
1411 /// Sets the read timeout for the socket.
1413 /// If the provided value is [`None`], then [`recv`] and [`recv_from`] calls will
1414 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`]
1415 /// is passed to this method.
1417 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
1418 /// [`Err`]: ../../../../std/result/enum.Result.html#variant.Err
1419 /// [`recv`]: #method.recv
1420 /// [`recv_from`]: #method.recv_from
1421 /// [`Duration`]: ../../../../std/time/struct.Duration.html
1426 /// use std::os::unix::net::UnixDatagram;
1427 /// use std::time::Duration;
1429 /// fn main() -> std::io::Result<()> {
1430 /// let sock = UnixDatagram::unbound()?;
1431 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1432 /// .expect("set_read_timeout function failed");
1437 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1442 /// use std::os::unix::net::UnixDatagram;
1443 /// use std::time::Duration;
1445 /// fn main() -> std::io::Result<()> {
1446 /// let socket = UnixDatagram::unbound()?;
1447 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1448 /// let err = result.unwrap_err();
1449 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1453 #[stable(feature = "unix_socket", since = "1.10.0")]
1454 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1455 self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
1458 /// Sets the write timeout for the socket.
1460 /// If the provided value is [`None`], then [`send`] and [`send_to`] calls will
1461 /// block indefinitely. An [`Err`] is returned if the zero [`Duration`] is passed to this
1464 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
1465 /// [`send`]: #method.send
1466 /// [`send_to`]: #method.send_to
1467 /// [`Duration`]: ../../../../std/time/struct.Duration.html
1472 /// use std::os::unix::net::UnixDatagram;
1473 /// use std::time::Duration;
1475 /// fn main() -> std::io::Result<()> {
1476 /// let sock = UnixDatagram::unbound()?;
1477 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1478 /// .expect("set_write_timeout function failed");
1483 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
1488 /// use std::os::unix::net::UnixDatagram;
1489 /// use std::time::Duration;
1491 /// fn main() -> std::io::Result<()> {
1492 /// let socket = UnixDatagram::unbound()?;
1493 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1494 /// let err = result.unwrap_err();
1495 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1499 #[stable(feature = "unix_socket", since = "1.10.0")]
1500 pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1501 self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
1504 /// Returns the read timeout of this socket.
1509 /// use std::os::unix::net::UnixDatagram;
1510 /// use std::time::Duration;
1512 /// fn main() -> std::io::Result<()> {
1513 /// let sock = UnixDatagram::unbound()?;
1514 /// sock.set_read_timeout(Some(Duration::new(1, 0)))
1515 /// .expect("set_read_timeout function failed");
1516 /// assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
1520 #[stable(feature = "unix_socket", since = "1.10.0")]
1521 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
1522 self.0.timeout(libc::SO_RCVTIMEO)
1525 /// Returns the write timeout of this socket.
1530 /// use std::os::unix::net::UnixDatagram;
1531 /// use std::time::Duration;
1533 /// fn main() -> std::io::Result<()> {
1534 /// let sock = UnixDatagram::unbound()?;
1535 /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1536 /// .expect("set_write_timeout function failed");
1537 /// assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
1541 #[stable(feature = "unix_socket", since = "1.10.0")]
1542 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
1543 self.0.timeout(libc::SO_SNDTIMEO)
1546 /// Moves the socket into or out of nonblocking mode.
1551 /// use std::os::unix::net::UnixDatagram;
1553 /// fn main() -> std::io::Result<()> {
1554 /// let sock = UnixDatagram::unbound()?;
1555 /// sock.set_nonblocking(true).expect("set_nonblocking function failed");
1559 #[stable(feature = "unix_socket", since = "1.10.0")]
1560 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1561 self.0.set_nonblocking(nonblocking)
1564 /// Returns the value of the `SO_ERROR` option.
1569 /// use std::os::unix::net::UnixDatagram;
1571 /// fn main() -> std::io::Result<()> {
1572 /// let sock = UnixDatagram::unbound()?;
1573 /// if let Ok(Some(err)) = sock.take_error() {
1574 /// println!("Got error: {:?}", err);
1579 #[stable(feature = "unix_socket", since = "1.10.0")]
1580 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1584 /// Shut down the read, write, or both halves of this connection.
1586 /// This function will cause all pending and future I/O calls on the
1587 /// specified portions to immediately return with an appropriate value
1588 /// (see the documentation of [`Shutdown`]).
1590 /// [`Shutdown`]: ../../../../std/net/enum.Shutdown.html
1593 /// use std::os::unix::net::UnixDatagram;
1594 /// use std::net::Shutdown;
1596 /// fn main() -> std::io::Result<()> {
1597 /// let sock = UnixDatagram::unbound()?;
1598 /// sock.shutdown(Shutdown::Both).expect("shutdown function failed");
1602 #[stable(feature = "unix_socket", since = "1.10.0")]
1603 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
1604 self.0.shutdown(how)
1608 #[stable(feature = "unix_socket", since = "1.10.0")]
1609 impl AsRawFd for UnixDatagram {
1610 fn as_raw_fd(&self) -> RawFd {
1615 #[stable(feature = "unix_socket", since = "1.10.0")]
1616 impl FromRawFd for UnixDatagram {
1617 unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
1618 UnixDatagram(Socket::from_inner(fd))
1622 #[stable(feature = "unix_socket", since = "1.10.0")]
1623 impl IntoRawFd for UnixDatagram {
1624 fn into_raw_fd(self) -> RawFd {
1629 #[cfg(all(test, not(target_os = "emscripten")))]
1631 use crate::io::prelude::*;
1632 use crate::io::{self, ErrorKind};
1633 use crate::sys_common::io::test::tmpdir;
1635 use crate::time::Duration;
1639 macro_rules! or_panic {
1643 Err(e) => panic!("{}", e),
1651 let socket_path = dir.path().join("sock");
1652 let msg1 = b"hello";
1653 let msg2 = b"world!";
1655 let listener = or_panic!(UnixListener::bind(&socket_path));
1656 let thread = thread::spawn(move || {
1657 let mut stream = or_panic!(listener.accept()).0;
1658 let mut buf = [0; 5];
1659 or_panic!(stream.read(&mut buf));
1660 assert_eq!(&msg1[..], &buf[..]);
1661 or_panic!(stream.write_all(msg2));
1664 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1665 assert_eq!(Some(&*socket_path), stream.peer_addr().unwrap().as_pathname());
1666 or_panic!(stream.write_all(msg1));
1667 let mut buf = vec![];
1668 or_panic!(stream.read_to_end(&mut buf));
1669 assert_eq!(&msg2[..], &buf[..]);
1672 thread.join().unwrap();
1677 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1679 let len = or_panic!(s1.write_vectored(&[
1680 IoSlice::new(b"hello"),
1682 IoSlice::new(b"world!")
1684 assert_eq!(len, 12);
1686 let mut buf1 = [0; 6];
1687 let mut buf2 = [0; 7];
1688 let len = or_panic!(
1689 s2.read_vectored(&mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)],)
1691 assert_eq!(len, 12);
1692 assert_eq!(&buf1, b"hello ");
1693 assert_eq!(&buf2, b"world!\0");
1698 let msg1 = b"hello";
1699 let msg2 = b"world!";
1701 let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1702 let thread = thread::spawn(move || {
1703 // s1 must be moved in or the test will hang!
1704 let mut buf = [0; 5];
1705 or_panic!(s1.read(&mut buf));
1706 assert_eq!(&msg1[..], &buf[..]);
1707 or_panic!(s1.write_all(msg2));
1710 or_panic!(s2.write_all(msg1));
1711 let mut buf = vec![];
1712 or_panic!(s2.read_to_end(&mut buf));
1713 assert_eq!(&msg2[..], &buf[..]);
1716 thread.join().unwrap();
1722 let socket_path = dir.path().join("sock");
1723 let msg1 = b"hello";
1724 let msg2 = b"world";
1726 let listener = or_panic!(UnixListener::bind(&socket_path));
1727 let thread = thread::spawn(move || {
1728 let mut stream = or_panic!(listener.accept()).0;
1729 or_panic!(stream.write_all(msg1));
1730 or_panic!(stream.write_all(msg2));
1733 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1734 let mut stream2 = or_panic!(stream.try_clone());
1736 let mut buf = [0; 5];
1737 or_panic!(stream.read(&mut buf));
1738 assert_eq!(&msg1[..], &buf[..]);
1739 or_panic!(stream2.read(&mut buf));
1740 assert_eq!(&msg2[..], &buf[..]);
1742 thread.join().unwrap();
1748 let socket_path = dir.path().join("sock");
1750 let listener = or_panic!(UnixListener::bind(&socket_path));
1751 let thread = thread::spawn(move || {
1752 for stream in listener.incoming().take(2) {
1753 let mut stream = or_panic!(stream);
1755 or_panic!(stream.read(&mut buf));
1760 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1761 or_panic!(stream.write_all(&[0]));
1764 thread.join().unwrap();
1770 let socket_path = dir.path().join(
1771 "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
1772 sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf",
1774 match UnixStream::connect(&socket_path) {
1775 Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1776 Err(e) => panic!("unexpected error {}", e),
1777 Ok(_) => panic!("unexpected success"),
1780 match UnixListener::bind(&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 UnixDatagram::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"),
1796 let socket_path = dir.path().join("sock");
1798 let _listener = or_panic!(UnixListener::bind(&socket_path));
1800 let stream = or_panic!(UnixStream::connect(&socket_path));
1801 let dur = Duration::new(15410, 0);
1803 assert_eq!(None, or_panic!(stream.read_timeout()));
1805 or_panic!(stream.set_read_timeout(Some(dur)));
1806 assert_eq!(Some(dur), or_panic!(stream.read_timeout()));
1808 assert_eq!(None, or_panic!(stream.write_timeout()));
1810 or_panic!(stream.set_write_timeout(Some(dur)));
1811 assert_eq!(Some(dur), or_panic!(stream.write_timeout()));
1813 or_panic!(stream.set_read_timeout(None));
1814 assert_eq!(None, or_panic!(stream.read_timeout()));
1816 or_panic!(stream.set_write_timeout(None));
1817 assert_eq!(None, or_panic!(stream.write_timeout()));
1821 fn test_read_timeout() {
1823 let socket_path = dir.path().join("sock");
1825 let _listener = or_panic!(UnixListener::bind(&socket_path));
1827 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1828 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1830 let mut buf = [0; 10];
1831 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1833 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1834 "unexpected_error: {:?}",
1840 fn test_read_with_timeout() {
1842 let socket_path = dir.path().join("sock");
1844 let listener = or_panic!(UnixListener::bind(&socket_path));
1846 let mut stream = or_panic!(UnixStream::connect(&socket_path));
1847 or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1849 let mut other_end = or_panic!(listener.accept()).0;
1850 or_panic!(other_end.write_all(b"hello world"));
1852 let mut buf = [0; 11];
1853 or_panic!(stream.read(&mut buf));
1854 assert_eq!(b"hello world", &buf[..]);
1856 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1858 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1859 "unexpected_error: {:?}",
1864 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1865 // when passed zero Durations
1867 fn test_unix_stream_timeout_zero_duration() {
1869 let socket_path = dir.path().join("sock");
1871 let listener = or_panic!(UnixListener::bind(&socket_path));
1872 let stream = or_panic!(UnixStream::connect(&socket_path));
1874 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1875 let err = result.unwrap_err();
1876 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1878 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1879 let err = result.unwrap_err();
1880 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1886 fn test_unix_datagram() {
1888 let path1 = dir.path().join("sock1");
1889 let path2 = dir.path().join("sock2");
1891 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1892 let sock2 = or_panic!(UnixDatagram::bind(&path2));
1894 let msg = b"hello world";
1895 or_panic!(sock1.send_to(msg, &path2));
1896 let mut buf = [0; 11];
1897 or_panic!(sock2.recv_from(&mut buf));
1898 assert_eq!(msg, &buf[..]);
1902 fn test_unnamed_unix_datagram() {
1904 let path1 = dir.path().join("sock1");
1906 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1907 let sock2 = or_panic!(UnixDatagram::unbound());
1909 let msg = b"hello world";
1910 or_panic!(sock2.send_to(msg, &path1));
1911 let mut buf = [0; 11];
1912 let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
1913 assert_eq!(usize, 11);
1914 assert!(addr.is_unnamed());
1915 assert_eq!(msg, &buf[..]);
1919 fn test_connect_unix_datagram() {
1921 let path1 = dir.path().join("sock1");
1922 let path2 = dir.path().join("sock2");
1924 let bsock1 = or_panic!(UnixDatagram::bind(&path1));
1925 let bsock2 = or_panic!(UnixDatagram::bind(&path2));
1926 let sock = or_panic!(UnixDatagram::unbound());
1927 or_panic!(sock.connect(&path1));
1930 let msg = b"hello there";
1931 or_panic!(sock.send(msg));
1932 let mut buf = [0; 11];
1933 let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
1934 assert_eq!(usize, 11);
1935 assert!(addr.is_unnamed());
1936 assert_eq!(msg, &buf[..]);
1938 // Changing default socket works too
1939 or_panic!(sock.connect(&path2));
1940 or_panic!(sock.send(msg));
1941 or_panic!(bsock2.recv_from(&mut buf));
1945 fn test_unix_datagram_recv() {
1947 let path1 = dir.path().join("sock1");
1949 let sock1 = or_panic!(UnixDatagram::bind(&path1));
1950 let sock2 = or_panic!(UnixDatagram::unbound());
1951 or_panic!(sock2.connect(&path1));
1953 let msg = b"hello world";
1954 or_panic!(sock2.send(msg));
1955 let mut buf = [0; 11];
1956 let size = or_panic!(sock1.recv(&mut buf));
1957 assert_eq!(size, 11);
1958 assert_eq!(msg, &buf[..]);
1962 fn datagram_pair() {
1963 let msg1 = b"hello";
1964 let msg2 = b"world!";
1966 let (s1, s2) = or_panic!(UnixDatagram::pair());
1967 let thread = thread::spawn(move || {
1968 // s1 must be moved in or the test will hang!
1969 let mut buf = [0; 5];
1970 or_panic!(s1.recv(&mut buf));
1971 assert_eq!(&msg1[..], &buf[..]);
1972 or_panic!(s1.send(msg2));
1975 or_panic!(s2.send(msg1));
1976 let mut buf = [0; 6];
1977 or_panic!(s2.recv(&mut buf));
1978 assert_eq!(&msg2[..], &buf[..]);
1981 thread.join().unwrap();
1984 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1985 // when passed zero Durations
1987 fn test_unix_datagram_timeout_zero_duration() {
1989 let path = dir.path().join("sock");
1991 let datagram = or_panic!(UnixDatagram::bind(&path));
1993 let result = datagram.set_write_timeout(Some(Duration::new(0, 0)));
1994 let err = result.unwrap_err();
1995 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1997 let result = datagram.set_read_timeout(Some(Duration::new(0, 0)));
1998 let err = result.unwrap_err();
1999 assert_eq!(err.kind(), ErrorKind::InvalidInput);
2003 fn abstract_namespace_not_allowed() {
2004 assert!(UnixStream::connect("\0asdf").is_err());