Expand description
Low-level network socket programming beyond std::net.
socket2 provides direct access to system socket APIs without requiring unsafe code.
Where std::net offers high-level TCP/UDP types,
socket2 exposes the full range of socket options, address families,
and configuration that the OS provides.
Common uses include setting socket options like SO_REUSEADDR or TCP_NODELAY,
configuring keepalive, creating dual-stack IPv6 listeners,
and converting the configured socket into standard library types.
The crate is maintained by the Rust project itself.
§Examples
Creating a TCP listener with socket options,
then converting to a std::net::TcpListener:
use socket2::{Socket, Domain, Type, Protocol, SockAddr};
use std::net::SocketAddr;
// Create a TCP socket.
let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?;
// Set SO_REUSEADDR so the port can be reused immediately after close.
socket.set_reuse_address(true)?;
// Bind to a local address.
let address: SocketAddr = "127.0.0.1:0".parse().unwrap();
socket.bind(&SockAddr::from(address))?;
// Start listening.
socket.listen(128)?;
// Convert to a std TcpListener for use with normal APIs.
let listener: std::net::TcpListener = socket.into();
let local_addr = listener.local_addr()?;
assert_eq!(local_addr.ip(), std::net::Ipv4Addr::LOCALHOST);Structs§
- Ccid
Endpoints - See
Socket::dccp_available_ccids. - Domain
- Specification of the communication domain for a socket.
- Maybe
Uninit Slice - A version of
IoSliceMutthat allows the buffer to be uninitialised. - MsgHdr
- Configuration of a
sendmsg(2)system call. - MsgHdr
Mut - Configuration of a
recvmsg(2)system call. - Protocol
- Protocol specification used for creating sockets via
Socket::new. - Recv
Flags - Flags for incoming messages.
- Sock
Addr - The address of a socket.
- Sock
Addr Storage - Rust version of the
sockaddr_storagetype. - Sock
Filter - Berkeley Packet Filter (BPF).
- SockRef
- A reference to a
Socketthat can be used to configure socket types other than theSockettype itself. - Socket
- Owned wrapper around a system socket.
- TcpKeepalive
- Configures a socket’s TCP keepalive parameters.
- Type
- Specification of communication semantics on a socket.
Enums§
- Interface
Index OrAddress - A local interface specified by its index or an address assigned to it.
Type Aliases§
- sa_
family_ t - The integer type for the
ss_familyfield on this platform. - socklen_
t - The integer type used with
getsocknameon this platform.