Struct std::os::unix::net::UnixDatagram

1.10.0 · source ·
pub struct UnixDatagram(_);
Available on Unix only.
Expand description

Unix 数据报套接字。

Examples

use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::bind("/path/to/my/socket")?;
    socket.send_to(b"hello world", "/path/to/other/socket")?;
    let mut buf = [0; 100];
    let (count, address) = socket.recv_from(&mut buf)?;
    println!("socket {:?} sent {:?}", address, &buf[..count]);
    Ok(())
}
Run

Implementations§

source§

impl UnixDatagram

source

pub fn bind<P: AsRef<Path>>(path: P) -> Result<UnixDatagram>

创建绑定到给定路径的 Unix 数据报套接字。

Examples
use std::os::unix::net::UnixDatagram;

let sock = match UnixDatagram::bind("/path/to/the/socket") {
    Ok(sock) => sock,
    Err(e) => {
        println!("Couldn't bind: {e:?}");
        return
    }
};
Run
1.70.0 · source

pub fn bind_addr(socket_addr: &SocketAddr) -> Result<UnixDatagram>

创建绑定到地址的 Unix 数据报套接字。

Examples
use std::os::unix::net::{UnixDatagram};

fn main() -> std::io::Result<()> {
    let sock1 = UnixDatagram::bind("path/to/socket")?;
    let addr = sock1.local_addr()?;

    let sock2 = match UnixDatagram::bind_addr(&addr) {
        Ok(sock) => sock,
        Err(err) => {
            println!("Couldn't bind: {err:?}");
            return Err(err);
        }
    };
    Ok(())
}
Run
source

pub fn unbound() -> Result<UnixDatagram>

创建未绑定到任何地址的 Unix 数据报套接字。

Examples
use std::os::unix::net::UnixDatagram;

let sock = match UnixDatagram::unbound() {
    Ok(sock) => sock,
    Err(e) => {
        println!("Couldn't unbound: {e:?}");
        return
    }
};
Run
source

pub fn pair() -> Result<(UnixDatagram, UnixDatagram)>

创建一对未命名的已连接套接字。

返回两个相互连接的 UnixDatagrams

Examples
use std::os::unix::net::UnixDatagram;

let (sock1, sock2) = match UnixDatagram::pair() {
    Ok((sock1, sock2)) => (sock1, sock2),
    Err(e) => {
        println!("Couldn't unbound: {e:?}");
        return
    }
};
Run
source

pub fn connect<P: AsRef<Path>>(&self, path: P) -> Result<()>

将套接字连接到指定的路径地址。

send 方法可用于将数据发送到指定的地址。 recvrecv_from 只会从该地址接收数据。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    match sock.connect("/path/to/the/socket") {
        Ok(sock) => sock,
        Err(e) => {
            println!("Couldn't connect: {e:?}");
            return Err(e)
        }
    };
    Ok(())
}
Run
1.70.0 · source

pub fn connect_addr(&self, socket_addr: &SocketAddr) -> Result<()>

将套接字连接到一个地址。

Examples
use std::os::unix::net::{UnixDatagram};

fn main() -> std::io::Result<()> {
    let bound = UnixDatagram::bind("/path/to/socket")?;
    let addr = bound.local_addr()?;

    let sock = UnixDatagram::unbound()?;
    match sock.connect_addr(&addr) {
        Ok(sock) => sock,
        Err(e) => {
            println!("Couldn't connect: {e:?}");
            return Err(e)
        }
    };
    Ok(())
}
Run
source

pub fn try_clone(&self) -> Result<UnixDatagram>

为底层套接字创建一个新的独立的拥有所有权的句柄。

返回的 UnixDatagram 是与此对象引用相同的套接字的引用。 两个句柄均可用于接受传入的连接,并且在一侧设置的选项会影响另一侧。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::bind("/path/to/the/socket")?;
    let sock_copy = sock.try_clone().expect("try_clone failed");
    Ok(())
}
Run
source

pub fn local_addr(&self) -> Result<SocketAddr>

返回此套接字的地址。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::bind("/path/to/the/socket")?;
    let addr = sock.local_addr().expect("Couldn't get local address");
    Ok(())
}
Run
source

pub fn peer_addr(&self) -> Result<SocketAddr>

返回此套接字的对等方的地址。

connect 方法会将套接字连接到对等方。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.connect("/path/to/the/socket")?;

    let addr = sock.peer_addr().expect("Couldn't get peer address");
    Ok(())
}
Run
source

pub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>

从套接字接收数据。

成功后,返回读取的字节数和数据到达的地址。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    let mut buf = vec![0; 10];
    let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
    println!("received {size} bytes from {sender:?}");
    Ok(())
}
Run
source

pub fn recv(&self, buf: &mut [u8]) -> Result<usize>

从套接字接收数据。

成功时,返回读取的字节数。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::bind("/path/to/the/socket")?;
    let mut buf = vec![0; 10];
    sock.recv(buf.as_mut_slice()).expect("recv function failed");
    Ok(())
}
Run
source

pub fn recv_vectored_with_ancillary_from( &self, bufs: &mut [IoSliceMut<'_>], ancillary: &mut SocketAncillary<'_> ) -> Result<(usize, bool, SocketAddr)>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

从套接字接收数据和辅助数据。

成功时,如果数据被截断,并且返回 msg 的地址,则返回读取的字节数。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixDatagram, SocketAncillary, AncillaryData};
use std::io::IoSliceMut;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    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, _truncated, sender) = sock.recv_vectored_with_ancillary_from(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(())
}
Run
source

pub fn recv_vectored_with_ancillary( &self, bufs: &mut [IoSliceMut<'_>], ancillary: &mut SocketAncillary<'_> ) -> Result<(usize, bool)>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

从套接字接收数据和辅助数据。

成功后,返回读取的字节数以及数据是否被截断。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixDatagram, SocketAncillary, AncillaryData};
use std::io::IoSliceMut;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    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, _truncated) = sock.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(())
}
Run
source

pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> Result<usize>

将套接字上的数据发送到指定地址。

成功时,返回写入的字节数。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
    Ok(())
}
Run
1.70.0 · source

pub fn send_to_addr( &self, buf: &[u8], socket_addr: &SocketAddr ) -> Result<usize>

将套接字上的数据发送到指定的 SocketAddr

成功时,返回写入的字节数。

Examples
use std::os::unix::net::{UnixDatagram};

fn main() -> std::io::Result<()> {
    let bound = UnixDatagram::bind("/path/to/socket")?;
    let addr = bound.local_addr()?;

    let sock = UnixDatagram::unbound()?;
    sock.send_to_addr(b"bacon egg and cheese", &addr).expect("send_to_addr function failed");
    Ok(())
}
Run
source

pub fn send(&self, buf: &[u8]) -> Result<usize>

将套接字上的数据发送到套接字的对等方。

可以通过 connect 方法设置对等地址,如果尚未连接套接字,则此方法将返回错误。

成功时,返回写入的字节数。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.connect("/some/sock").expect("Couldn't connect");
    sock.send(b"omelette au fromage").expect("send_to function failed");
    Ok(())
}
Run
source

pub fn send_vectored_with_ancillary_to<P: AsRef<Path>>( &self, bufs: &[IoSlice<'_>], ancillary: &mut SocketAncillary<'_>, path: P ) -> Result<usize>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

将套接字上的数据和辅助数据发送到指定地址。

成功时,返回写入的字节数。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixDatagram, SocketAncillary};
use std::io::IoSlice;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    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[..]);
    sock.send_vectored_with_ancillary_to(bufs, &mut ancillary, "/some/sock")
        .expect("send_vectored_with_ancillary_to function failed");
    Ok(())
}
Run
source

pub fn send_vectored_with_ancillary( &self, bufs: &[IoSlice<'_>], ancillary: &mut SocketAncillary<'_> ) -> Result<usize>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

在套接字上发送数据和辅助数据。

成功时,返回写入的字节数。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixDatagram, SocketAncillary};
use std::io::IoSlice;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    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[..]);
    sock.send_vectored_with_ancillary(bufs, &mut ancillary)
        .expect("send_vectored_with_ancillary function failed");
    Ok(())
}
Run
source

pub fn set_read_timeout(&self, timeout: Option<Duration>) -> Result<()>

设置套接字的读取超时。

如果提供的值为 None,则 recvrecv_from 调用将无限期阻塞。 如果将零 Duration 传递给此方法,则返回 Err

Examples
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_read_timeout(Some(Duration::new(1, 0)))
        .expect("set_read_timeout function failed");
    Ok(())
}
Run

如果将零 Duration 传递给此方法,则返回 Err

use std::io;
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::unbound()?;
    let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
    let err = result.unwrap_err();
    assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    Ok(())
}
Run
source

pub fn set_write_timeout(&self, timeout: Option<Duration>) -> Result<()>

设置套接字的写超时。

如果提供的值为 None,则 sendsend_to 调用将无限期阻塞。 如果将零 Duration 传递给此方法,则返回 Err

Examples
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_write_timeout(Some(Duration::new(1, 0)))
        .expect("set_write_timeout function failed");
    Ok(())
}
Run

如果将零 Duration 传递给此方法,则返回 Err

use std::io;
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::unbound()?;
    let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
    let err = result.unwrap_err();
    assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    Ok(())
}
Run
source

pub fn read_timeout(&self) -> Result<Option<Duration>>

返回此套接字的读取超时。

Examples
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_read_timeout(Some(Duration::new(1, 0)))
        .expect("set_read_timeout function failed");
    assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
    Ok(())
}
Run
source

pub fn write_timeout(&self) -> Result<Option<Duration>>

返回此套接字的写入超时。

Examples
use std::os::unix::net::UnixDatagram;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_write_timeout(Some(Duration::new(1, 0)))
        .expect("set_write_timeout function failed");
    assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
    Ok(())
}
Run
source

pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>

将套接字移入或移出非阻塞模式。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_nonblocking(true).expect("set_nonblocking function failed");
    Ok(())
}
Run
source

pub fn set_passcred(&self, passcred: bool) -> Result<()>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

移动套接字以将 unix 凭据作为 SocketAncillary 中的控制消息传递。

设置套接字选项 SO_PASSCRED

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_passcred (true).expect ("set_passcred 函数失败");
    Ok(())
}
Run
source

pub fn passcred(&self) -> Result<bool>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

获取用于在 SocketAncillary 中传递 unix 凭据的套接字的当前值。 可以通过 set_passcred 更改此值。

获取套接字选项 SO_PASSCRED

source

pub fn set_mark(&self, mark: u32) -> Result<()>

🔬This is a nightly-only experimental API. (unix_set_mark #96467)

设置套接字的 id 以进行网络过滤

#![feature(unix_set_mark)]
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.set_mark(32)?;
    Ok(())
}
Run
source

pub fn take_error(&self) -> Result<Option<Error>>

返回 SO_ERROR 选项的值。

Examples
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    if let Ok(Some(err)) = sock.take_error() {
        println!("Got error: {err:?}");
    }
    Ok(())
}
Run
source

pub fn shutdown(&self, how: Shutdown) -> Result<()>

关闭此连接的读取,写入或两部分。

此函数将导致对指定部分的所有未决和 future I/O 调用立即返回适当的值 (请参见 Shutdown 的文档)。

use std::os::unix::net::UnixDatagram;
use std::net::Shutdown;

fn main() -> std::io::Result<()> {
    let sock = UnixDatagram::unbound()?;
    sock.shutdown(Shutdown::Both).expect("shutdown function failed");
    Ok(())
}
Run
source

pub fn peek(&self, buf: &mut [u8]) -> Result<usize>

🔬This is a nightly-only experimental API. (unix_socket_peek #76923)

从套接字所连接的远程地址接收套接字上的数据,而无需从队列中删除该数据。

成功时,返回偷看的字节数。

连续调用返回相同的数据。 这是通过将 MSG_PEEK 作为标志传递给底层的 recv 系统调用来实现的。

Examples
#![feature(unix_socket_peek)]

use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::bind("/tmp/sock")?;
    let mut buf = [0; 10];
    let len = socket.peek(&mut buf).expect("peek failed");
    Ok(())
}
Run
source

pub fn peek_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>

🔬This is a nightly-only experimental API. (unix_socket_peek #76923)

在套接字上接收单个数据报消息,而无需将其从队列中删除。 成功时,返回读取的字节数和源。

必须使用足够大的有效字节数组 buf 来调用函数,以容纳消息字节。 如果消息太长而无法容纳在提供的缓冲区中,则多余的字节可能会被丢弃。

连续调用返回相同的数据。 这是通过将 MSG_PEEK 作为标志传递到底层的 recvfrom 系统调用来实现的。

不要使用此函数来实现繁忙等待,而应使用 libc::poll 来同步一个或多个套接字上的 IO 事件。

Examples
#![feature(unix_socket_peek)]

use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::bind("/tmp/sock")?;
    let mut buf = [0; 10];
    let (len, addr) = socket.peek_from(&mut buf).expect("peek failed");
    Ok(())
}
Run

Trait Implementations§

1.63.0 · source§

impl AsFd for UnixDatagram

source§

fn as_fd(&self) -> BorrowedFd<'_>

借用文件描述符。 Read more
source§

impl AsRawFd for UnixDatagram

source§

fn as_raw_fd(&self) -> RawFd

提取原始文件描述符。 Read more
source§

impl Debug for UnixDatagram

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

使用给定的格式化程序格式化该值。 Read more
1.63.0 · source§

impl From<OwnedFd> for UnixDatagram

source§

fn from(owned: OwnedFd) -> Self

从输入类型转换为此类型。
1.63.0 · source§

impl From<UnixDatagram> for OwnedFd

source§

fn from(unix_datagram: UnixDatagram) -> OwnedFd

从输入类型转换为此类型。
source§

impl FromRawFd for UnixDatagram

source§

unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram

根据给定的原始文件描述符构造 Self 的新实例。 Read more
source§

impl IntoRawFd for UnixDatagram

source§

fn into_raw_fd(self) -> RawFd

消费这个对象,返回原始的底层文件描述符。 Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

获取 selfTypeIdRead more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

从拥有的值中一成不变地借用。 Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

从拥有的值中借用。 Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

返回未更改的参数。

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

调用 U::from(self)

也就是说,这种转换是 From<T> for U 实现选择执行的任何操作。

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

发生转换错误时返回的类型。
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

发生转换错误时返回的类型。
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。