Skip to main content

Module socket2

Module socket2 

Source
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§

CcidEndpoints
See Socket::dccp_available_ccids.
Domain
Specification of the communication domain for a socket.
MaybeUninitSlice
A version of IoSliceMut that allows the buffer to be uninitialised.
MsgHdr
Configuration of a sendmsg(2) system call.
MsgHdrMut
Configuration of a recvmsg(2) system call.
Protocol
Protocol specification used for creating sockets via Socket::new.
RecvFlags
Flags for incoming messages.
SockAddr
The address of a socket.
SockAddrStorage
Rust version of the sockaddr_storage type.
SockFilter
Berkeley Packet Filter (BPF).
SockRef
A reference to a Socket that can be used to configure socket types other than the Socket type 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§

InterfaceIndexOrAddress
A local interface specified by its index or an address assigned to it.

Type Aliases§

sa_family_t
The integer type for the ss_family field on this platform.
socklen_t
The integer type used with getsockname on this platform.