Struct Socket
struct Socket { ... }
Owned wrapper around a system socket.
This type simply wraps an instance of a file descriptor (c_int) on Unix
and an instance of SOCKET on Windows. This is the main type exported by
this crate and is intended to mirror the raw semantics of sockets on
platforms as closely as possible. Almost all methods correspond to
precisely one libc or OS API call which is essentially just a "Rustic
translation" of what's below.
Converting to and from other types
This type can be freely converted into the network primitives provided by
the standard library, such as TcpStream or UdpSocket, using the
From trait, see the example below.
Notes
Some methods that set options on Socket require two system calls to set
their options without overwriting previously set options. We do this by
first getting the current settings, applying the desired changes, and then
updating the settings. This means that the operation is not atomic. This
can lead to a data race when two threads are changing options in parallel.
Examples
# fn main() -> std::io::Result<()> {
use std::net::{SocketAddr, TcpListener};
use socket2::{Socket, Domain, Type};
// create a TCP listener
let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
let address: SocketAddr = "[::1]:12345".parse().unwrap();
let address = address.into();
socket.bind(&address)?;
socket.listen(128)?;
let listener: TcpListener = socket.into();
// ...
# drop(listener);
# Ok(()) }
Implementations
impl Socket
fn join_multicast_v6(self: &Self, multiaddr: &Ipv6Addr, interface: u32) -> Result<()>Join a multicast group using
IPV6_ADD_MEMBERSHIPoption on this socket.Some OSs use
IPV6_JOIN_GROUPfor this option.This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and
interfaceis the index of the interface to join/leave (or 0 to indicate any interface).fn leave_multicast_v6(self: &Self, multiaddr: &Ipv6Addr, interface: u32) -> Result<()>Leave a multicast group using
IPV6_DROP_MEMBERSHIPoption on this socket.Some OSs use
IPV6_LEAVE_GROUPfor this option.For more information about this option, see
join_multicast_v6.fn multicast_hops_v6(self: &Self) -> Result<u32>Get the value of the
IPV6_MULTICAST_HOPSoption for this socketFor more information about this option, see
set_multicast_hops_v6.fn set_multicast_hops_v6(self: &Self, hops: u32) -> Result<()>Set the value of the
IPV6_MULTICAST_HOPSoption for this socketIndicates the number of "routers" multicast packets will transit for this socket. The default value is 1 which means that multicast packets don't leave the local network unless explicitly requested.
fn multicast_if_v6(self: &Self) -> Result<u32>Get the value of the
IPV6_MULTICAST_IFoption for this socket.For more information about this option, see
set_multicast_if_v6.fn set_multicast_if_v6(self: &Self, interface: u32) -> Result<()>Set the value of the
IPV6_MULTICAST_IFoption for this socket.Specifies the interface to use for routing multicast packets. Unlike ipv4, this is generally required in ipv6 contexts where network routing prefixes may overlap.
fn multicast_loop_v6(self: &Self) -> Result<bool>Get the value of the
IPV6_MULTICAST_LOOPoption for this socket.For more information about this option, see
set_multicast_loop_v6.fn set_multicast_loop_v6(self: &Self, loop_v6: bool) -> Result<()>Set the value of the
IPV6_MULTICAST_LOOPoption for this socket.Controls whether this socket sees the multicast packets it sends itself. Note that this may not have any affect on IPv4 sockets.
fn unicast_hops_v6(self: &Self) -> Result<u32>Get the value of the
IPV6_UNICAST_HOPSoption for this socket.Specifies the hop limit for ipv6 unicast packets
fn set_unicast_hops_v6(self: &Self, hops: u32) -> Result<()>Set the value for the
IPV6_UNICAST_HOPSoption on this socket.Specifies the hop limit for ipv6 unicast packets
fn only_v6(self: &Self) -> Result<bool>Get the value of the
IPV6_V6ONLYoption for this socket.For more information about this option, see
set_only_v6.fn set_only_v6(self: &Self, only_v6: bool) -> Result<()>Set the value for the
IPV6_V6ONLYoption on this socket.If this is set to
truethen the socket is restricted to sending and receiving IPv6 packets only. In this case two IPv4 and IPv6 applications can bind the same port at the same time.If this is set to
falsethen the socket can be used to send and receive packets from an IPv4-mapped IPv6 address.fn recv_tclass_v6(self: &Self) -> Result<bool>Get the value of the
IPV6_RECVTCLASSoption for this socket.For more information about this option, see
set_recv_tclass_v6.fn set_recv_tclass_v6(self: &Self, recv_tclass: bool) -> Result<()>Set the value of the
IPV6_RECVTCLASSoption for this socket.If enabled, the
IPV6_TCLASSancillary message is passed with incoming packets. It contains a byte which specifies the traffic class field of the packet header.
impl Socket
fn set_tcp_keepalive(self: &Self, params: &TcpKeepalive) -> Result<()>Set parameters configuring TCP keepalive probes for this socket.
The supported parameters depend on the operating system, and are configured using the
TcpKeepalivestruct. At a minimum, all systems support configuring the keepalive time: the time after which the OS will start sending keepalive messages on an idle connection.Notes
- This will enable
SO_KEEPALIVEon this socket, if it is not already enabled. - On some platforms, such as Windows, any keepalive parameters not
configured by the
TcpKeepalivestruct passed to this function may be overwritten with their default values. Therefore, this function should either only be called once per socket, or the same parameters should be passed every time it is called.
Examples
use Duration; use ; #- This will enable
fn tcp_nodelay(self: &Self) -> Result<bool>Get the value of the
TCP_NODELAYoption on this socket.For more information about this option, see
set_tcp_nodelay.fn set_tcp_nodelay(self: &Self, nodelay: bool) -> Result<()>Set the value of the
TCP_NODELAYoption on this socket.If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets.
impl Socket
fn broadcast(self: &Self) -> Result<bool>Get the value of the
SO_BROADCASToption for this socket.For more information about this option, see
set_broadcast.fn set_broadcast(self: &Self, broadcast: bool) -> Result<()>Set the value of the
SO_BROADCASToption for this socket.When enabled, this socket is allowed to send packets to a broadcast address.
fn take_error(self: &Self) -> Result<Option<Error>>Get the value of the
SO_ERRORoption on this socket.This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.
fn keepalive(self: &Self) -> Result<bool>Get the value of the
SO_KEEPALIVEoption on this socket.For more information about this option, see
set_keepalive.fn set_keepalive(self: &Self, keepalive: bool) -> Result<()>Set value for the
SO_KEEPALIVEoption on this socket.Enable sending of keep-alive messages on connection-oriented sockets.
fn linger(self: &Self) -> Result<Option<Duration>>Get the value of the
SO_LINGERoption on this socket.For more information about this option, see
set_linger.fn set_linger(self: &Self, linger: Option<Duration>) -> Result<()>Set value for the
SO_LINGERoption on this socket.If
lingeris notNone, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of exit(2), it always lingers in the background.Notes
On most OSs the duration only has a precision of seconds and will be silently truncated.
On Apple platforms (e.g. macOS, iOS, etc) this uses
SO_LINGER_SEC.fn out_of_band_inline(self: &Self) -> Result<bool>Get value for the
SO_OOBINLINEoption on this socket.For more information about this option, see
set_out_of_band_inline.fn set_out_of_band_inline(self: &Self, oob_inline: bool) -> Result<()>Set value for the
SO_OOBINLINEoption on this socket.If this option is enabled, out-of-band data is directly placed into the receive data stream. Otherwise, out-of-band data is passed only when the
MSG_OOBflag is set during receiving. As per RFC6093, TCP sockets using the Urgent mechanism are encouraged to set this flag.fn passcred(self: &Self) -> Result<bool>Get value for the
SO_PASSCREDoption on this socket.For more information about this option, see
set_passcred.fn set_passcred(self: &Self, passcred: bool) -> Result<()>Set value for the
SO_PASSCREDoption on this socket.If this option is enabled, enables the receiving of the
SCM_CREDENTIALScontrol messages.fn recv_buffer_size(self: &Self) -> Result<usize>Get value for the
SO_RCVBUFoption on this socket.For more information about this option, see
set_recv_buffer_size.fn set_recv_buffer_size(self: &Self, size: usize) -> Result<()>Set value for the
SO_RCVBUFoption on this socket.Changes the size of the operating system's receive buffer associated with the socket.
fn read_timeout(self: &Self) -> Result<Option<Duration>>Get value for the
SO_RCVTIMEOoption on this socket.If the returned timeout is
None, thenreadandrecvcalls will block indefinitely.fn set_read_timeout(self: &Self, duration: Option<Duration>) -> Result<()>Set value for the
SO_RCVTIMEOoption on this socket.If
timeoutisNone, thenreadandrecvcalls will block indefinitely.fn reuse_address(self: &Self) -> Result<bool>Get the value of the
SO_REUSEADDRoption on this socket.For more information about this option, see
set_reuse_address.fn set_reuse_address(self: &Self, reuse: bool) -> Result<()>Set value for the
SO_REUSEADDRoption on this socket.This indicates that further calls to
bindmay allow reuse of local addresses. For IPv4 sockets this means that a socket may bind even when there's a socket already listening on this port.fn send_buffer_size(self: &Self) -> Result<usize>Get the value of the
SO_SNDBUFoption on this socket.For more information about this option, see
set_send_buffer_size.fn set_send_buffer_size(self: &Self, size: usize) -> Result<()>Set value for the
SO_SNDBUFoption on this socket.Changes the size of the operating system's send buffer associated with the socket.
fn write_timeout(self: &Self) -> Result<Option<Duration>>Get value for the
SO_SNDTIMEOoption on this socket.If the returned timeout is
None, thenwriteandsendcalls will block indefinitely.fn set_write_timeout(self: &Self, duration: Option<Duration>) -> Result<()>Set value for the
SO_SNDTIMEOoption on this socket.If
timeoutisNone, thenwriteandsendcalls will block indefinitely.
impl Socket
fn join_multicast_v4(self: &Self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> Result<()>Join a multicast group using
IP_ADD_MEMBERSHIPoption on this socket.This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and
interfaceis the address of the local interface with which the system should join the multicast group. If it'sIpv4Addr::UNSPECIFIED(INADDR_ANY) then an appropriate interface is chosen by the system.fn leave_multicast_v4(self: &Self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> Result<()>Leave a multicast group using
IP_DROP_MEMBERSHIPoption on this socket.For more information about this option, see
join_multicast_v4.fn join_multicast_v4_n(self: &Self, multiaddr: &Ipv4Addr, interface: &InterfaceIndexOrAddress) -> Result<()>Join a multicast group using
IP_ADD_MEMBERSHIPoption on this socket.This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and
interfacespecifies the local interface with which the system should join the multicast group. SeeInterfaceIndexOrAddress.fn leave_multicast_v4_n(self: &Self, multiaddr: &Ipv4Addr, interface: &InterfaceIndexOrAddress) -> Result<()>Leave a multicast group using
IP_DROP_MEMBERSHIPoption on this socket.For more information about this option, see
join_multicast_v4_n.fn join_ssm_v4(self: &Self, source: &Ipv4Addr, group: &Ipv4Addr, interface: &Ipv4Addr) -> Result<()>Join a multicast SSM channel using
IP_ADD_SOURCE_MEMBERSHIPoption on this socket.This function specifies a new multicast channel for this socket to join. The group must be a valid SSM group address, the source must be the address of the sender and
interfaceis the address of the local interface with which the system should join the multicast group. If it'sIpv4Addr::UNSPECIFIED(INADDR_ANY) then an appropriate interface is chosen by the system.fn leave_ssm_v4(self: &Self, source: &Ipv4Addr, group: &Ipv4Addr, interface: &Ipv4Addr) -> Result<()>Leave a multicast group using
IP_DROP_SOURCE_MEMBERSHIPoption on this socket.For more information about this option, see
join_ssm_v4.fn multicast_if_v4(self: &Self) -> Result<Ipv4Addr>Get the value of the
IP_MULTICAST_IFoption for this socket.For more information about this option, see
set_multicast_if_v4.fn set_multicast_if_v4(self: &Self, interface: &Ipv4Addr) -> Result<()>Set the value of the
IP_MULTICAST_IFoption for this socket.Specifies the interface to use for routing multicast packets.
fn multicast_loop_v4(self: &Self) -> Result<bool>Get the value of the
IP_MULTICAST_LOOPoption for this socket.For more information about this option, see
set_multicast_loop_v4.fn set_multicast_loop_v4(self: &Self, loop_v4: bool) -> Result<()>Set the value of the
IP_MULTICAST_LOOPoption for this socket.If enabled, multicast packets will be looped back to the local socket. Note that this may not have any affect on IPv6 sockets.
fn multicast_ttl_v4(self: &Self) -> Result<u32>Get the value of the
IP_MULTICAST_TTLoption for this socket.For more information about this option, see
set_multicast_ttl_v4.fn set_multicast_ttl_v4(self: &Self, ttl: u32) -> Result<()>Set the value of the
IP_MULTICAST_TTLoption for this socket.Indicates the time-to-live value of outgoing multicast packets for this socket. The default value is 1 which means that multicast packets don't leave the local network unless explicitly requested.
Note that this may not have any affect on IPv6 sockets.
fn ttl_v4(self: &Self) -> Result<u32>Get the value of the
IP_TTLoption for this socket.For more information about this option, see
set_ttl_v4.fn set_ttl_v4(self: &Self, ttl: u32) -> Result<()>Set the value of the
IP_TTLoption for this socket.This value sets the time-to-live field that is used in every packet sent from this socket.
fn set_tos_v4(self: &Self, tos: u32) -> Result<()>Set the value of the
IP_TOSoption for this socket.This value sets the type-of-service field that is used in every packet sent from this socket.
NOTE: https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options documents that not all versions of windows support
IP_TOS.fn tos_v4(self: &Self) -> Result<u32>Get the value of the
IP_TOSoption for this socket.For more information about this option, see
set_tos_v4.NOTE: https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options documents that not all versions of windows support
IP_TOS.fn set_recv_tos_v4(self: &Self, recv_tos: bool) -> Result<()>Set the value of the
IP_RECVTOSoption for this socket.If enabled, the
IP_TOSancillary message is passed with incoming packets. It contains a byte which specifies the Type of Service/Precedence field of the packet header.fn recv_tos_v4(self: &Self) -> Result<bool>Get the value of the
IP_RECVTOSoption for this socket.For more information about this option, see
set_recv_tos_v4.
impl Socket
fn new(domain: Domain, ty: Type, protocol: Option<Protocol>) -> Result<Socket>Creates a new socket and sets common flags.
This function corresponds to
socket(2)on Unix andWSASocketWon Windows.On Unix-like systems, the close-on-exec flag is set on the new socket. Additionally, on Apple platforms
SOCK_NOSIGPIPEis set. On Windows, the socket is made non-inheritable.Socket::new_rawcan be used if you don't want these flags to be set.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=socket§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=socket&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/socket.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/socket.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/socket.2
- OpenBSD: https://man.openbsd.org/socket.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/socket.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/socket
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket
fn new_raw(domain: Domain, ty: Type, protocol: Option<Protocol>) -> Result<Socket>Creates a new socket ready to be configured.
This function corresponds to
socket(2)on Unix andWSASocketWon Windows and simply creates a new socket, no other configuration is done.fn bind(self: &Self, address: &SockAddr) -> Result<()>Binds this socket to the specified address.
This function directly corresponds to the
bind(2)function on Windows and Unix.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=bind§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=bind&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/bind.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/bind.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/bind.2
- OpenBSD: https://man.openbsd.org/bind.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/bind.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/bind
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind
fn connect(self: &Self, address: &SockAddr) -> Result<()>Initiate a connection on this socket to the specified address.
This function directly corresponds to the
connect(2)function on Windows and Unix.An error will be returned if
listenorconnecthas already been called on this builder.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=connect§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=connect&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/connect.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/connect.2
- OpenBSD: https://man.openbsd.org/connect.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/connect
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect
Notes
When using a non-blocking connect (by setting the socket into non-blocking mode before calling this function), socket option can't be set while connecting. This will cause errors on Windows. Socket options can be safely set before and after connecting the socket.
On Cygwin, a Unix domain socket connect blocks until the server accepts it. If the behavior is not expected, try
Socket::set_no_peercred(Cygwin only).fn connect_timeout(self: &Self, addr: &SockAddr, timeout: Duration) -> Result<()>Initiate a connection on this socket to the specified address, only only waiting for a certain period of time for the connection to be established.
Unlike many other methods on
Socket, this does not correspond to a single C function. It sets the socket to nonblocking mode, connects via connect(2), and then waits for the connection to complete with poll(2) on Unix and select on Windows. When the connection is complete, the socket is set back to blocking mode. On Unix, this will loop overEINTRerrors.Warnings
The non-blocking state of the socket is overridden by this function - it will be returned in blocking mode on success, and in an indeterminate state on failure.
If the connection request times out, it may still be processing in the background - a second call to
connectorconnect_timeoutmay fail.fn listen(self: &Self, backlog: c_int) -> Result<()>Mark a socket as ready to accept incoming connection requests using [
Socket::accept()].This function directly corresponds to the
listen(2)function on Windows and Unix.An error will be returned if
listenorconnecthas already been called on this builder.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=listen§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=listen&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/listen.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/listen.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/listen.2
- OpenBSD: https://man.openbsd.org/listen.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/listen.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/listen
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-listen
fn accept(self: &Self) -> Result<(Socket, SockAddr)>Accept a new incoming connection from this listener.
This function uses
accept4(2)on platforms that support it andaccept(2)platforms that do not.This function sets the same flags as in done for
Socket::new,Socket::accept_rawcan be used if you don't want to set those flags.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=accept§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=accept&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/accept.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/accept.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/accept.2
- OpenBSD: https://man.openbsd.org/accept.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/accept.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/accept
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept
Notes
On Cygwin, a Unix domain socket connect blocks until the server accepts it. If the behavior is not expected, try
Socket::set_no_peercred(Cygwin only).fn accept_raw(self: &Self) -> Result<(Socket, SockAddr)>Accept a new incoming connection from this listener.
This function directly corresponds to the
accept(2)function on Windows and Unix.fn local_addr(self: &Self) -> Result<SockAddr>Returns the socket address of the local half of this socket.
This function directly corresponds to the
getsockname(2)function on Windows and Unix.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=getsockname§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=getsockname&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/getsockname.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getsockname.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/getsockname.2
- OpenBSD: https://man.openbsd.org/getsockname.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getsockname.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/getsockname
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-getsockname
Notes
Depending on the OS this may return an error if the socket is not bound.
fn peer_addr(self: &Self) -> Result<SockAddr>Returns the socket address of the remote peer of this socket.
This function directly corresponds to the
getpeername(2)function on Windows and Unix.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=getpeername§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=getpeername&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/getpeername.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpeername.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/getpeername.2
- OpenBSD: https://man.openbsd.org/getpeername.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpeername.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/getpeername
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-getpeername
Notes
This returns an error if the socket is not
connected.fn type(self: &Self) -> Result<Type>Returns the
Typeof this socket by checking theSO_TYPEoption on this socket.fn try_clone(self: &Self) -> Result<Socket>Creates a new independently owned handle to the underlying socket.
Notes
On Unix this uses
F_DUPFD_CLOEXECand thus sets theFD_CLOEXECon the returned socket.On Windows this uses
WSA_FLAG_NO_HANDLE_INHERITsetting inheriting to false.On Windows this can not be used function cannot be used on a QOS-enabled socket, see https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaduplicatesocketw.
fn set_nonblocking(self: &Self, nonblocking: bool) -> Result<()>Moves this socket into or out of nonblocking mode.
Notes
On Unix this corresponds to calling
fcntl(un)settingO_NONBLOCK.On Windows this corresponds to calling
ioctlsocket(un)settingFIONBIO.fn shutdown(self: &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 on the specified portions to return immediately with an appropriate value.
Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=shutdown§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=shutdown&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/shutdown.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/shutdown.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/shutdown.2
- OpenBSD: https://man.openbsd.org/shutdown.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/shutdown.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/shutdown
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-shutdown
fn recv(self: &Self, buf: &mut [MaybeUninit<u8>]) -> Result<usize>Receives data on the socket from the remote address to which it is connected.
The
connectmethod will connect this socket to a remote address. This method might fail if the socket is not connected.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=recv§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=recv&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/recv.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recv.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/recv.2
- OpenBSD: https://man.openbsd.org/recv.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recv.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/recv
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recv
Safety
Normally casting a
&mut [u8]to&mut [MaybeUninit<u8>]would be unsound, as that allows us to write uninitialised bytes to the buffer. However this implementation promises to not write uninitialised bytes to thebuffer and passes it directly torecv(2)system call. This promise ensures that this function can be called using abuffer of type&mut [u8].Note that the
io::Read::readimplementation calls this function with abuffer of type&mut [u8], allowing initialised buffers to be used without usingunsafe.fn recv_out_of_band(self: &Self, buf: &mut [MaybeUninit<u8>]) -> Result<usize>Receives out-of-band (OOB) data on the socket from the remote address to which it is connected by setting the
MSG_OOBflag for this call.For more information, see
recv,out_of_band_inline.fn recv_with_flags(self: &Self, buf: &mut [MaybeUninit<u8>], flags: c_int) -> Result<usize>Identical to
recvbut allows for specification of arbitrary flags to the underlyingrecvcall.fn recv_vectored(self: &Self, bufs: &mut [MaybeUninitSlice<'_>]) -> Result<(usize, RecvFlags)>Receives data on the socket from the remote address to which it is connected. Unlike
recvthis allows passing multiple buffers.The
connectmethod will connect this socket to a remote address. This method might fail if the socket is not connected.In addition to the number of bytes read, this function returns the flags for the received message. See
RecvFlagsfor more information about the returned flags.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=recvmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=recvmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/recvmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/recvmsg.2
- OpenBSD: https://man.openbsd.org/recvmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/recvmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvmsg
Safety
Normally casting a
IoSliceMuttoMaybeUninitSlicewould be unsound, as that allows us to write uninitialised bytes to the buffer. However this implementation promises to not write uninitialised bytes to thebufsand passes it directly torecvmsg(2)system call. This promise ensures that this function can be called usingbufsof type&mut [IoSliceMut].Note that the
io::Read::read_vectoredimplementation calls this function withbufs of type&mut [IoSliceMut], allowing initialised buffers to be used without usingunsafe.fn recv_vectored_with_flags(self: &Self, bufs: &mut [MaybeUninitSlice<'_>], flags: c_int) -> Result<(usize, RecvFlags)>Identical to
recv_vectoredbut allows for specification of arbitrary flags to the underlyingrecvmsg/WSARecvcall.Safety
recv_from_vectoredmakes the same safety guarantees regardingbufsasrecv_vectored.fn peek(self: &Self, buf: &mut [MaybeUninit<u8>]) -> Result<usize>Receives data on the socket from the remote adress 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.Safety
peekmakes the same safety guarantees regarding thebuffer asrecv.fn recv_from(self: &Self, buf: &mut [MaybeUninit<u8>]) -> Result<(usize, SockAddr)>Receives data from the socket. On success, returns the number of bytes read and the address from whence the data came.
Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=recvfrom§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=recvfrom&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/recvfrom.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvfrom.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/recvfrom.2
- OpenBSD: https://man.openbsd.org/recvfrom.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvfrom.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/recvfrom
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvfrom
Safety
recv_frommakes the same safety guarantees regarding thebuffer asrecv.fn recv_from_with_flags(self: &Self, buf: &mut [MaybeUninit<u8>], flags: c_int) -> Result<(usize, SockAddr)>Identical to
recv_frombut allows for specification of arbitrary flags to the underlyingrecvfromcall.fn recv_from_vectored(self: &Self, bufs: &mut [MaybeUninitSlice<'_>]) -> Result<(usize, RecvFlags, SockAddr)>Receives data from the socket. Returns the amount of bytes read, the
RecvFlagsand the remote address from the data is coming. Unlikerecv_fromthis allows passing multiple buffers.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=recvmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=recvmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/recvmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/recvmsg.2
- OpenBSD: https://man.openbsd.org/recvmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/recvmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvmsg
Safety
recv_from_vectoredmakes the same safety guarantees regardingbufsasrecv_vectored.fn recv_from_vectored_with_flags(self: &Self, bufs: &mut [MaybeUninitSlice<'_>], flags: c_int) -> Result<(usize, RecvFlags, SockAddr)>Identical to
recv_from_vectoredbut allows for specification of arbitrary flags to the underlyingrecvmsg/WSARecvFromcall.Safety
recv_from_vectoredmakes the same safety guarantees regardingbufsasrecv_vectored.fn peek_from(self: &Self, buf: &mut [MaybeUninit<u8>]) -> Result<(usize, SockAddr)>Receives data from the socket, without removing it from the queue.
Successive calls return the same data. This is accomplished by passing
MSG_PEEKas a flag to the underlyingrecvfromsystem call.On success, returns the number of bytes peeked and the address from whence the data came.
Safety
peek_frommakes the same safety guarantees regarding thebuffer asrecv.Note: Datagram Sockets
For datagram sockets, the behavior of this method when
bufis smaller than the datagram at the head of the receive queue differs between Windows and Unix-like platforms (Linux, macOS, BSDs, etc: colloquially termed "*nix").On *nix platforms, the datagram is truncated to the length of
buf.On Windows, an error corresponding to
WSAEMSGSIZEwill be returned.For consistency between platforms, be sure to provide a sufficiently large buffer to avoid truncation; the exact size required depends on the underlying protocol.
If you just want to know the sender of the data, try
peek_sender.fn peek_sender(self: &Self) -> Result<SockAddr>Retrieve the sender for the data at the head of the receive queue.
This is equivalent to calling
peek_fromwith a zero-sized buffer, but suppresses theWSAEMSGSIZEerror on Windows.fn recvmsg(self: &Self, msg: &mut MsgHdrMut<'_, '_, '_>, flags: c_int) -> Result<usize>Receive a message from a socket using a message structure.
This is not supported on Windows as calling
WSARecvMsg(therecvmsgequivalent) is not straight forward on Windows. See https://github.com/microsoft/Windows-classic-samples/blob/7cbd99ac1d2b4a0beffbaba29ea63d024ceff700/Samples/Win7Samples/netds/winsock/recvmsg/rmmc.cpp for an example (in C++).Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=recvmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=recvmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/recvmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/recvmsg.2
- OpenBSD: https://man.openbsd.org/recvmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/recvmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvmsg
fn send(self: &Self, buf: &[u8]) -> Result<usize>Sends data on the socket to a connected peer.
This is typically used on TCP sockets or datagram sockets which have been connected.
On success returns the number of bytes that were sent.
Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=send§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=send&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/send.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/send.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/send.2
- OpenBSD: https://man.openbsd.org/send.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/send.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/send
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send
fn send_with_flags(self: &Self, buf: &[u8], flags: c_int) -> Result<usize>Identical to
sendbut allows for specification of arbitrary flags to the underlyingsendcall.fn send_vectored(self: &Self, bufs: &[IoSlice<'_>]) -> Result<usize>Send data to the connected peer. Returns the amount of bytes written.
fn send_vectored_with_flags(self: &Self, bufs: &[IoSlice<'_>], flags: c_int) -> Result<usize>Identical to
send_vectoredbut allows for specification of arbitrary flags to the underlyingsendmsg/WSASendcall.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=sendmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/sendmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/sendmsg.2
- OpenBSD: https://man.openbsd.org/sendmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/sendmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendmsg
fn send_out_of_band(self: &Self, buf: &[u8]) -> Result<usize>Sends out-of-band (OOB) data on the socket to connected peer by setting the
MSG_OOBflag for this call.For more information, see
send,out_of_band_inline.fn send_to(self: &Self, buf: &[u8], addr: &SockAddr) -> Result<usize>Sends data on the socket to the given address. On success, returns the number of bytes written.
This is typically used on UDP or datagram-oriented sockets.
Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=sendto§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=sendto&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/sendto.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendto.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/sendto.2
- OpenBSD: https://man.openbsd.org/sendto.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendto.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/sendto
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendto
fn send_to_with_flags(self: &Self, buf: &[u8], addr: &SockAddr, flags: c_int) -> Result<usize>Identical to
send_tobut allows for specification of arbitrary flags to the underlyingsendtocall.fn send_to_vectored(self: &Self, bufs: &[IoSlice<'_>], addr: &SockAddr) -> Result<usize>Send data to a peer listening on
addr. Returns the amount of bytes written.Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=sendmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/sendmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/sendmsg.2
- OpenBSD: https://man.openbsd.org/sendmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/sendmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendmsg
fn send_to_vectored_with_flags(self: &Self, bufs: &[IoSlice<'_>], addr: &SockAddr, flags: c_int) -> Result<usize>Identical to
send_to_vectoredbut allows for specification of arbitrary flags to the underlyingsendmsg/WSASendTocall.fn sendmsg(self: &Self, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> Result<usize>Send a message on a socket using a message structure.
Additional documentation can be found in manual of the OS:
- DragonFly BSD: https://man.dragonflybsd.org/?command=sendmsg§ion=2
- FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
- Linux: https://man7.org/linux/man-pages/man2/sendmsg.2.html
- macOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived, actually for iOS)
- NetBSD: https://man.netbsd.org/sendmsg.2
- OpenBSD: https://man.openbsd.org/sendmsg.2
- iOS: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html (archived)
- illumos: https://illumos.org/man/3SOCKET/sendmsg
- Windows: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendmsg
impl AsFd for Socket
fn as_fd(self: &Self) -> BorrowedFd<'_>
impl AsRawFd for Socket
fn as_raw_fd(self: &Self) -> RawFd
impl Debug for Socket
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Freeze for Socket
impl From for Socket
fn from(socket: TcpStream) -> Socket
impl From for Socket
fn from(socket: UdpSocket) -> Socket
impl From for Socket
fn from(socket: TcpListener) -> Socket
impl From for Socket
fn from(fd: OwnedFd) -> Socket
impl FromRawFd for Socket
unsafe fn from_raw_fd(fd: c_int) -> Socket
impl IntoRawFd for Socket
fn into_raw_fd(self: Self) -> c_int
impl Read for Socket
fn read(self: &mut Self, buf: &mut [u8]) -> Result<usize>fn read_vectored(self: &mut Self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
impl RefUnwindSafe for Socket
impl Send for Socket
impl Sync for Socket
impl Unpin for Socket
impl UnsafeUnpin for Socket
impl UnwindSafe for Socket
impl Write for Socket
fn write(self: &mut Self, buf: &[u8]) -> Result<usize>fn write_vectored(self: &mut Self, bufs: &[IoSlice<'_>]) -> Result<usize>fn flush(self: &mut Self) -> Result<()>
impl<T> Any for Socket
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Socket
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Socket
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for Socket
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for Socket
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Socket
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Socket
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>