Struct UnixStream
pub struct UnixStream(pub(in ::os::unix::net) Socket);
A Unix stream socket.
Examples
use std::os::unix::net::UnixStream;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut stream = UnixStream::connect("/path/to/my/socket")?;
stream.write_all(b"hello world")?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
println!("{response}");
Ok(())
}
SOCK_CLOEXEC
On platforms that support it, we pass the close-on-exec flag to atomically create the socket and
set it as CLOEXEC. On Linux, this was added in 2.6.27. See socket(2) for more information.
SIGPIPE
Writes to the underlying socket in SOCK_STREAM mode are made with MSG_NOSIGNAL flag.
This suppresses the emission of the SIGPIPE signal when writing to disconnected socket.
In some cases getting a SIGPIPE would trigger process termination.
Fields
0: Socket
Implementations
impl UnixStream
fn connect<P: AsRef<Path>>(path: P) -> Result<UnixStream>Connects to the socket named by
path.Examples
use std::os::unix::net::UnixStream; let socket = match UnixStream::connect("/tmp/sock") { Ok(sock) => sock, Err(e) => { println!("Couldn't connect: {e:?}"); return } };fn connect_addr(socket_addr: &SocketAddr) -> Result<UnixStream>Connects to the socket specified by
address.Examples
use std::os::unix::net::{UnixListener, UnixStream}; fn main() -> std::io::Result<()> { let listener = UnixListener::bind("/path/to/the/socket")?; let addr = listener.local_addr()?; let sock = match UnixStream::connect_addr(&addr) { Ok(sock) => sock, Err(e) => { println!("Couldn't connect: {e:?}"); return Err(e) } }; Ok(()) }fn pair() -> Result<(UnixStream, UnixStream)>Creates an unnamed pair of connected sockets.
Returns two
UnixStreams which are connected to each other.Examples
use std::os::unix::net::UnixStream; let (sock1, sock2) = match UnixStream::pair() { Ok((sock1, sock2)) => (sock1, sock2), Err(e) => { println!("Couldn't create a pair of sockets: {e:?}"); return } };fn try_clone(&self) -> Result<UnixStream>Creates a new independently owned handle to the underlying socket.
The returned
UnixStreamis a reference to the same stream that this object references. Both handles will read and write the same stream of data, and options set on one stream will be propagated to the other stream.Examples
use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let sock_copy = socket.try_clone().expect("Couldn't clone socket"); Ok(()) }fn local_addr(&self) -> Result<SocketAddr>Returns the socket address of the local half of this connection.
Examples
use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let addr = socket.local_addr().expect("Couldn't get local address"); Ok(()) }fn peer_addr(&self) -> Result<SocketAddr>Returns the socket address of the remote half of this connection.
Examples
use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let addr = socket.peer_addr().expect("Couldn't get peer address"); Ok(()) }fn peer_cred(&self) -> Result<UCred>Gets the peer credentials for this Unix domain socket.
Examples
#![feature(peer_credentials_unix_socket)] use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let peer_cred = socket.peer_cred().expect("Couldn't get peer credentials"); Ok(()) }fn set_read_timeout(&self, timeout: Option<Duration>) -> Result<()>Sets the read timeout for the socket.
If the provided value is
None, thenreadcalls will block indefinitely. AnErris returned if the zeroDurationis passed to this method.Examples
use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout"); Ok(()) }An
Erris returned if the zeroDurationis passed to this method:use std::io; use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let result = socket.set_read_timeout(Some(Duration::new(0, 0))); let err = result.unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput); Ok(()) }fn set_write_timeout(&self, timeout: Option<Duration>) -> Result<()>Sets the write timeout for the socket.
If the provided value is
None, thenwritecalls will block indefinitely. AnErris returned if the zeroDurationis passed to this method.Examples
use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.set_write_timeout(Some(Duration::new(1, 0))) .expect("Couldn't set write timeout"); Ok(()) }An
Erris returned if the zeroDurationis passed to this method:use std::io; use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let result = socket.set_write_timeout(Some(Duration::new(0, 0))); let err = result.unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput); Ok(()) }fn read_timeout(&self) -> Result<Option<Duration>>Returns the read timeout of this socket.
Examples
use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout"); assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0))); Ok(()) }fn write_timeout(&self) -> Result<Option<Duration>>Returns the write timeout of this socket.
Examples
use std::os::unix::net::UnixStream; use std::time::Duration; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.set_write_timeout(Some(Duration::new(1, 0))) .expect("Couldn't set write timeout"); assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0))); Ok(()) }fn set_nonblocking(&self, nonblocking: bool) -> Result<()>Moves the socket into or out of nonblocking mode.
Examples
use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.set_nonblocking(true).expect("Couldn't set nonblocking"); Ok(()) }fn set_mark(&self, mark: u32) -> Result<()>Set the id of the socket for network filtering purpose
#![feature(unix_set_mark)] use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let sock = UnixStream::connect("/tmp/sock")?; sock.set_mark(32)?; Ok(()) }fn take_error(&self) -> Result<Option<Error>>Returns the value of the
SO_ERRORoption.Examples
use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; if let Ok(Some(err)) = socket.take_error() { println!("Got error: {err:?}"); } Ok(()) }Platform specific
On Redox this always returns
None.fn shutdown(&self, how: Shutdown) -> Result<()>Shuts down the read, write, or both halves of this connection.
This function will cause all pending and future I/O calls on the specified portions to immediately return with an appropriate value (see the documentation of
Shutdown).Examples
use std::os::unix::net::UnixStream; use std::net::Shutdown; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; socket.shutdown(Shutdown::Both).expect("shutdown function failed"); Ok(()) }fn peek(&self, buf: &mut [u8]) -> Result<usize>Receives data on the socket from the remote address to which it is connected, without removing that data from the queue. On success, returns the number of bytes peeked.
Successive calls return the same data. This is accomplished by passing
MSG_PEEKas a flag to the underlyingrecvsystem call.Examples
#![feature(unix_socket_peek)] use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let mut buf = [0; 10]; let len = socket.peek(&mut buf).expect("peek failed"); Ok(()) }fn recv_vectored_with_ancillary(&self, bufs: &mut [IoSliceMut<'_>], ancillary: &mut SocketAncillary<'_>) -> Result<usize>Receives data and ancillary data from socket.
On success, returns the number of bytes read.
Examples
#![feature(unix_socket_ancillary_data)] use std::os::unix::net::{UnixStream, SocketAncillary, AncillaryData}; use std::io::IoSliceMut; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let mut buf1 = [1; 8]; let mut buf2 = [2; 16]; let mut buf3 = [3; 8]; let mut bufs = &mut [ IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2), IoSliceMut::new(&mut buf3), ][..]; let mut fds = [0; 8]; let mut ancillary_buffer = [0; 128]; let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]); let size = socket.recv_vectored_with_ancillary(bufs, &mut ancillary)?; println!("received {size}"); for ancillary_result in ancillary.messages() { if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { for fd in scm_rights { println!("receive file descriptor: {fd}"); } } } Ok(()) }fn send_vectored_with_ancillary(&self, bufs: &[IoSlice<'_>], ancillary: &mut SocketAncillary<'_>) -> Result<usize>Sends data and ancillary data on the socket.
On success, returns the number of bytes written.
Examples
#![feature(unix_socket_ancillary_data)] use std::os::unix::net::{UnixStream, SocketAncillary}; use std::io::IoSlice; fn main() -> std::io::Result<()> { let socket = UnixStream::connect("/tmp/sock")?; let buf1 = [1; 8]; let buf2 = [2; 16]; let buf3 = [3; 8]; let bufs = &[ IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3), ][..]; let fds = [0, 1, 2]; let mut ancillary_buffer = [0; 128]; let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]); ancillary.add_fds(&fds[..]); socket.send_vectored_with_ancillary(bufs, &mut ancillary) .expect("send_vectored_with_ancillary function failed"); Ok(()) }
Trait Implementations
impl AsFd for UnixStream
fn as_fd(&self) -> BorrowedFd<'_>
impl AsInner<Socket> for UnixStream
fn as_inner(&self) -> &Socket
impl AsRawFd for UnixStream
fn as_raw_fd(&self) -> RawFd
impl CopyRead for UnixStream
fn properties(&self) -> CopyParams
impl CopyWrite for UnixStream
fn properties(&self) -> CopyParams
impl Debug for UnixStream
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result
impl From<OwnedFd> for UnixStream
fn from(owned: OwnedFd) -> Self
impl FromRawFd for UnixStream
unsafe fn from_raw_fd(fd: RawFd) -> UnixStream
impl IntoRawFd for UnixStream
fn into_raw_fd(self) -> RawFd
impl Read for UnixStream
fn read(&mut self, buf: &mut [u8]) -> Result<usize>fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>fn is_read_vectored(&self) -> bool
impl SpecCopy for UnixStream
fn copy<R: Read + ?Sized, W: Write + ?Sized>(read: &mut R, write: &mut W) -> Result<CopyState>
impl UnixSocketExt for UnixStream
fn passcred(&self) -> Result<bool>fn set_passcred(&self, passcred: bool) -> Result<()>
impl Write for UnixStream
fn write(&mut self, buf: &[u8]) -> Result<usize>fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>fn is_write_vectored(&self) -> boolfn flush(&mut self) -> Result<()>
Auto Trait Implementations
impl Freeze for UnixStream
impl RefUnwindSafe for UnixStream
impl Send for UnixStream
impl Sync for UnixStream
impl Unpin for UnixStream
impl UnsafeUnpin for UnixStream
impl UnwindSafe for UnixStream
Blanket Implementations
impl<R> SpecReadByte for UnixStream
where
R: Read,
fn spec_read_byte(&mut self) -> Option<Result<u8, Error>>
impl<T> Any for UnixStream
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for UnixStream
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for UnixStream
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> From<T> for UnixStream
fn from(t: T) -> TReturns the argument unchanged.
impl<T> SizeHint for UnixStream
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for UnixStream
impl<T, U> Into<U> for UnixStream
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for UnixStream
where
U: Into<T>,
type Error = Infallible;fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for UnixStream
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>