Struct TcpSocket
struct TcpSocket { ... }
A TCP socket that has not yet been converted to a TcpStream or
TcpListener.
TcpSocket wraps an operating system socket and enables the caller to
configure the socket before establishing a TCP connection or accepting
inbound connections. The caller is able to set socket option and explicitly
bind the socket with a socket address.
The underlying socket is closed when the TcpSocket value is dropped.
TcpSocket should only be used directly if the default configuration used
by TcpStream::connect and TcpListener::bind does not meet the required
use case.
Calling TcpStream::connect("127.0.0.1:8080") is equivalent to:
use tokio::net::TcpSocket;
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let addr = "127.0.0.1:8080".parse().unwrap();
let socket = TcpSocket::new_v4()?;
let stream = socket.connect(addr).await?;
# drop(stream);
Ok(())
}
Calling TcpListener::bind("127.0.0.1:8080") is equivalent to:
use tokio::net::TcpSocket;
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let addr = "127.0.0.1:8080".parse().unwrap();
let socket = TcpSocket::new_v4()?;
// On platforms with Berkeley-derived sockets, this allows to quickly
// rebind a socket, without needing to wait for the OS to clean up the
// previous one.
//
// On Windows, this allows rebinding sockets which are actively in use,
// which allows "socket hijacking", so we explicitly don't set it here.
// https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
socket.set_reuseaddr(true)?;
socket.bind(addr)?;
let listener = socket.listen(1024)?;
# drop(listener);
Ok(())
}
Setting socket options not explicitly provided by TcpSocket may be done by
accessing the RawFd/RawSocket using AsRawFd/AsRawSocket and
setting the option with a crate like socket2.
Implementations
impl TcpSocket
fn new_v4() -> Result<TcpSocket>Creates a new socket configured for IPv4.
Calls
socket(2)withAF_INETandSOCK_STREAM.Returns
On success, the newly created
TcpSocketis returned. If an error is encountered, it is returned instead.Examples
Create a new IPv4 socket and start listening.
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; let listener = socket.listen(128)?; # drop(listener); Ok(()) }fn new_v6() -> Result<TcpSocket>Creates a new socket configured for IPv6.
Calls
socket(2)withAF_INET6andSOCK_STREAM.Returns
On success, the newly created
TcpSocketis returned. If an error is encountered, it is returned instead.Examples
Create a new IPv6 socket and start listening.
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "[::1]:8080".parse().unwrap(); let socket = TcpSocket::new_v6()?; socket.bind(addr)?; let listener = socket.listen(128)?; # drop(listener); Ok(()) }fn set_keepalive(self: &Self, keepalive: bool) -> Result<()>Sets value for the
SO_KEEPALIVEoption on this socket.fn keepalive(self: &Self) -> Result<bool>Gets the value of the
SO_KEEPALIVEoption on this socket.fn set_reuseaddr(self: &Self, reuseaddr: bool) -> Result<()>Allows the socket to bind to an in-use address.
Behavior is platform specific. Refer to the target platform's documentation for more details.
Examples
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.set_reuseaddr(true)?; socket.bind(addr)?; let listener = socket.listen(1024)?; # drop(listener); Ok(()) }fn reuseaddr(self: &Self) -> Result<bool>Retrieves the value set for
SO_REUSEADDRon this socket.Examples
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.set_reuseaddr(true)?; assert!(socket.reuseaddr().unwrap()); socket.bind(addr)?; let listener = socket.listen(1024)?; Ok(()) }fn set_reuseport(self: &Self, reuseport: bool) -> Result<()>Allows the socket to bind to an in-use port. Only available for unix systems (excluding Solaris & Illumos).
Behavior is platform specific. Refer to the target platform's documentation for more details.
Examples
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.set_reuseport(true)?; socket.bind(addr)?; let listener = socket.listen(1024)?; Ok(()) }fn reuseport(self: &Self) -> Result<bool>Allows the socket to bind to an in-use port. Only available for unix systems (excluding Solaris & Illumos).
Behavior is platform specific. Refer to the target platform's documentation for more details.
Examples
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.set_reuseport(true)?; assert!(socket.reuseport().unwrap()); socket.bind(addr)?; let listener = socket.listen(1024)?; Ok(()) }fn set_send_buffer_size(self: &Self, size: u32) -> Result<()>Sets the size of the TCP send buffer on this socket.
On most operating systems, this sets the
SO_SNDBUFsocket option.fn send_buffer_size(self: &Self) -> Result<u32>Returns the size of the TCP send buffer for this socket.
On most operating systems, this is the value of the
SO_SNDBUFsocket option.Note that if
set_send_buffer_sizehas been called on this socket previously, the value returned by this function may not be the same as the argument provided toset_send_buffer_size. This is for the following reasons:- Most operating systems have minimum and maximum allowed sizes for the send buffer, and will clamp the provided value if it is below the minimum or above the maximum. The minimum and maximum buffer sizes are OS-dependent.
- Linux will double the buffer size to account for internal bookkeeping
data, and returns the doubled value from
getsockopt(2). As perman 7 socket:Sets or gets the maximum socket send buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using
setsockopt(2), and this doubled value is returned bygetsockopt(2).
fn set_recv_buffer_size(self: &Self, size: u32) -> Result<()>Sets the size of the TCP receive buffer on this socket.
On most operating systems, this sets the
SO_RCVBUFsocket option.fn recv_buffer_size(self: &Self) -> Result<u32>Returns the size of the TCP receive buffer for this socket.
On most operating systems, this is the value of the
SO_RCVBUFsocket option.Note that if
set_recv_buffer_sizehas been called on this socket previously, the value returned by this function may not be the same as the argument provided toset_recv_buffer_size. This is for the following reasons:- Most operating systems have minimum and maximum allowed sizes for the receive buffer, and will clamp the provided value if it is below the minimum or above the maximum. The minimum and maximum buffer sizes are OS-dependent.
- Linux will double the buffer size to account for internal bookkeeping
data, and returns the doubled value from
getsockopt(2). As perman 7 socket:Sets or gets the maximum socket send buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using
setsockopt(2), and this doubled value is returned bygetsockopt(2).
fn set_linger(self: &Self, dur: Option<Duration>) -> Result<()>Sets the linger duration of this socket by setting the
SO_LINGERoption.This option controls the action taken when a stream has unsent messages and the stream is closed. If
SO_LINGERis set, the system shall block the process until it can transmit the data or until the time expires.If
SO_LINGERis not specified, and the socket is closed, the system handles the call in a way that allows the process to continue as quickly as possible.fn linger(self: &Self) -> Result<Option<Duration>>Reads the linger duration for this socket by getting the
SO_LINGERoption.For more information about this option, see
set_linger.fn set_nodelay(self: &Self, nodelay: bool) -> Result<()>Sets 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.
Examples
use tokio::net::TcpSocket; # async fn dox() -> Result<(), Box<dyn std::error::Error>> { let socket = TcpSocket::new_v4()?; socket.set_nodelay(true)?; # Ok(()) # }fn nodelay(self: &Self) -> Result<bool>Gets the value of the
TCP_NODELAYoption on this socket.For more information about this option, see
set_nodelay.Examples
use tokio::net::TcpSocket; # async fn dox() -> Result<(), Box<dyn std::error::Error>> { let socket = TcpSocket::new_v4()?; println!("{:?}", socket.nodelay()?); # Ok(()) # }fn tos(self: &Self) -> Result<u32>Gets the value of the
IP_TOSoption for this socket.For more information about this option, see
set_tos.NOTE: On Windows,
IP_TOSis only supported on Windows 8+ or Windows Server 2012+.fn set_tos(self: &Self, tos: u32) -> Result<()>Sets the value for the
IP_TOSoption on this socket.This value sets the type-of-service field that is used in every packet sent from this socket.
NOTE: On Windows,
IP_TOSis only supported on Windows 8+ or Windows Server 2012+.fn device(self: &Self) -> Result<Option<Vec<u8>>>Gets the value for the
SO_BINDTODEVICEoption on this socketThis value gets the socket binded device's interface name.
fn bind_device(self: &Self, interface: Option<&[u8]>) -> Result<()>Sets the value for the
SO_BINDTODEVICEoption on this socketIf a socket is bound to an interface, only packets received from that particular interface are processed by the socket. Note that this only works for some socket types, particularly
AF_INETsockets.If
interfaceisNoneor an empty string it removes the binding.fn local_addr(self: &Self) -> Result<SocketAddr>Gets the local address of this socket.
Will fail on windows if called before
bind.Examples
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; assert_eq!(socket.local_addr().unwrap().to_string(), "127.0.0.1:8080"); let listener = socket.listen(1024)?; Ok(()) }fn take_error(self: &Self) -> Result<Option<Error>>Returns the value of the
SO_ERRORoption.fn bind(self: &Self, addr: SocketAddr) -> Result<()>Binds the socket to the given address.
This calls the
bind(2)operating-system function. Behavior is platform specific. Refer to the target platform's documentation for more details.Examples
Bind a socket before listening.
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; let listener = socket.listen(1024)?; # drop(listener); Ok(()) }async fn connect(self: Self, addr: SocketAddr) -> Result<TcpStream>Establishes a TCP connection with a peer at the specified socket address.
The
TcpSocketis consumed. Once the connection is established, a connectedTcpStreamis returned. If the connection fails, the encountered error is returned.This calls the
connect(2)operating-system function. Behavior is platform specific. Refer to the target platform's documentation for more details.Examples
Connecting to a peer.
use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; let stream = socket.connect(addr).await?; # drop(stream); Ok(()) }fn listen(self: Self, backlog: u32) -> Result<TcpListener>Converts the socket into a
TcpListener.backlogdefines the maximum number of pending connections are queued by the operating system at any given time. Connection are removed from the queue withTcpListener::accept. When the queue is full, the operating-system will start rejecting connections.This calls the
listen(2)operating-system function, marking the socket as a passive socket. Behavior is platform specific. Refer to the target platform's documentation for more details.Examples
Create a
TcpListener.use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; let listener = socket.listen(1024)?; # drop(listener); Ok(()) }fn from_std_stream(std_stream: TcpStream) -> TcpSocketConverts a
std::net::TcpStreaminto aTcpSocket. The provided socket must not have been connected prior to calling this function. This function is typically used together with crates such assocket2to configure socket options that are not available onTcpSocket.Notes
The caller is responsible for ensuring that the socket is in non-blocking mode. Otherwise all I/O operations on the socket will block the thread, which will cause unexpected behavior. Non-blocking mode can be set using
set_nonblocking.Examples
use TcpSocket; use ; async
impl AsFd for TcpSocket
fn as_fd(self: &Self) -> BorrowedFd<'_>
impl AsRawFd for TcpSocket
fn as_raw_fd(self: &Self) -> RawFd
impl Debug for TcpSocket
fn fmt(self: &Self, fmt: &mut Formatter<'_>) -> Result
impl Freeze for TcpSocket
impl FromRawFd for TcpSocket
unsafe fn from_raw_fd(fd: RawFd) -> TcpSocketConverts a
RawFdto aTcpSocket.Notes
The caller is responsible for ensuring that the socket is in non-blocking mode.
impl IntoRawFd for TcpSocket
fn into_raw_fd(self: Self) -> RawFd
impl RefUnwindSafe for TcpSocket
impl Send for TcpSocket
impl Sync for TcpSocket
impl Unpin for TcpSocket
impl UnsafeUnpin for TcpSocket
impl UnwindSafe for TcpSocket
impl<T> Any for TcpSocket
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for TcpSocket
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for TcpSocket
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for TcpSocket
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for TcpSocket
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 TcpSocket
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for TcpSocket
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>