Skip to main content

TcpSocket

Struct TcpSocket 

Source
pub struct TcpSocket { /* private fields */ }
Available on non-loom and non-WASI only.
Expand description

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?;

    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)?;

    // Note: the actual backlog used by `TcpListener::bind` is platform-dependent,
    // as Tokio relies on Mio's default backlog value configuration. The `1024` here is only
    // illustrative and does not reflect the real value used.
    let listener = socket.listen(1024)?;

    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§

Source§

impl TcpSocket

Source

pub fn new_v4() -> Result<TcpSocket>

Available on crate feature net only.

Creates a new socket configured for IPv4.

Calls socket(2) with AF_INET and SOCK_STREAM.

§Returns

On success, the newly created TcpSocket is 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)?;
    Ok(())
}
Source

pub fn new_v6() -> Result<TcpSocket>

Available on crate feature net only.

Creates a new socket configured for IPv6.

Calls socket(2) with AF_INET6 and SOCK_STREAM.

§Returns

On success, the newly created TcpSocket is 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)?;
    Ok(())
}
Source

pub fn set_keepalive(&self, keepalive: bool) -> Result<()>

Available on crate feature net only.

Sets value for the SO_KEEPALIVE option on this socket.

Source

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

Available on crate feature net only.

Gets the value of the SO_KEEPALIVE option on this socket.

Source

pub fn set_reuseaddr(&self, reuseaddr: bool) -> Result<()>

Available on crate feature net only.

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)?;

    Ok(())
}
Source

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

Available on crate feature net only.

Retrieves the value set for SO_REUSEADDR on 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(())
}
Source

pub fn set_reuseport(&self, reuseport: bool) -> Result<()>

Available on Unix and non-Solaris and non-illumos and non-Cygwin and crate feature net only.

Allows the socket to bind to an in-use port. Only available for unix systems (excluding Solaris, Illumos, and Cygwin).

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(())
}
Source

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

Available on Unix and non-Solaris and non-illumos and non-Cygwin and crate feature net only.

Allows the socket to bind to an in-use port. Only available for unix systems (excluding Solaris, Illumos, and Cygwin).

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(())
}
Source

pub fn set_send_buffer_size(&self, size: u32) -> Result<()>

Available on crate feature net only.

Sets the size of the TCP send buffer on this socket.

On most operating systems, this sets the SO_SNDBUF socket option.

Source

pub fn send_buffer_size(&self) -> Result<u32>

Available on crate feature net only.

Returns the size of the TCP send buffer for this socket.

On most operating systems, this is the value of the SO_SNDBUF socket option.

Note that if set_send_buffer_size has been called on this socket previously, the value returned by this function may not be the same as the argument provided to set_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 per man 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 by getsockopt(2).

Source

pub fn set_recv_buffer_size(&self, size: u32) -> Result<()>

Available on crate feature net only.

Sets the size of the TCP receive buffer on this socket.

On most operating systems, this sets the SO_RCVBUF socket option.

Source

pub fn recv_buffer_size(&self) -> Result<u32>

Available on crate feature net only.

Returns the size of the TCP receive buffer for this socket.

On most operating systems, this is the value of the SO_RCVBUF socket option.

Note that if set_recv_buffer_size has been called on this socket previously, the value returned by this function may not be the same as the argument provided to set_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 per man 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 by getsockopt(2).

Source

pub fn set_linger(&self, dur: Option<Duration>) -> Result<()>

👎Deprecated: SO_LINGER causes the socket to block the thread on drop
Available on crate feature net only.

Sets the linger duration of this socket by setting the SO_LINGER option.

This option controls the action taken when a stream has unsent messages and the stream is closed. If SO_LINGER is set, the system shall block the process until it can transmit the data or until the time expires.

If SO_LINGER is 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.

This option is deprecated because setting SO_LINGER on a socket used with Tokio is always incorrect as it leads to blocking the thread when the socket is closed. For more details, please see:

Volumes of communications have been devoted to the intricacies of SO_LINGER versus non-blocking (O_NONBLOCK) sockets. From what I can tell, the final word is: don’t do it. Rely on the shutdown()-followed-by-read()-eof technique instead.

From The ultimate SO_LINGER page, or: why is my tcp not reliable

Although this method is deprecated, it will not be removed from Tokio.

Note that the special case of setting SO_LINGER to zero does not lead to blocking. Tokio provides set_zero_linger for this purpose.

Source

pub fn set_zero_linger(&self) -> Result<()>

Available on crate feature net only.

Sets a linger duration of zero on this socket by setting the SO_LINGER option.

This causes the connection to be forcefully aborted (“abortive close”) when the socket is dropped or closed. Instead of the normal TCP shutdown handshake (FIN/ACK), a TCP RST (reset) segment is sent to the peer, and the socket immediately discards any unsent data residing in the socket send buffer. This prevents the socket from entering the TIME_WAIT state after closing it.

This is a destructive action. Any data currently buffered by the OS but not yet transmitted will be lost. The peer will likely receive a “Connection Reset” error rather than a clean end-of-stream.

See the documentation for set_linger for additional details on how SO_LINGER works.

Source

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

Available on crate feature net only.

Reads the linger duration for this socket by getting the SO_LINGER option.

For more information about this option, see set_zero_linger and set_linger.

Source

pub fn set_nodelay(&self, nodelay: bool) -> Result<()>

Available on crate feature net only.

Sets the value of the TCP_NODELAY option 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;

let socket = TcpSocket::new_v4()?;

socket.set_nodelay(true)?;
Source

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

Available on crate feature net only.

Gets the value of the TCP_NODELAY option on this socket.

For more information about this option, see set_nodelay.

§Examples
use tokio::net::TcpSocket;

let socket = TcpSocket::new_v4()?;

println!("{:?}", socket.nodelay()?);
Source

pub fn tclass_v6(&self) -> Result<u32>

Available on crate feature net and (Android or DragonFly BSD or FreeBSD or Fuchsia or Linux or macOS or NetBSD or OpenBSD or Cygwin) only.

Gets the value of the IPV6_TCLASS option for this socket.

For more information about this option, see set_tclass_v6.

Source

pub fn set_tclass_v6(&self, tclass: u32) -> Result<()>

Available on crate feature net and (Android or DragonFly BSD or FreeBSD or Fuchsia or Linux or macOS or NetBSD or OpenBSD or Cygwin) only.

Sets the value for the IPV6_TCLASS option on this socket.

Specifies the traffic class field that is used in every packet sent from this socket.

§Note

This may not have any effect on IPv4 sockets.

Source

pub fn tos_v4(&self) -> Result<u32>

Available on crate feature net and neither Fuchsia nor Redox nor Solaris nor illumos nor Haiku only.

Gets the value of the IP_TOS option for this socket.

For more information about this option, see set_tos_v4.

Source

pub fn set_tos_v4(&self, tos: u32) -> Result<()>

Available on crate feature net and neither Fuchsia nor Redox nor Solaris nor illumos nor Haiku only.

Sets the value for the IP_TOS option on this socket.

This value sets the type-of-service field that is used in every packet sent from this socket.

§Note
Source

pub fn device(&self) -> Result<Option<Vec<u8>>>

Available on crate feature net and (Android or Fuchsia or Linux) only.

Gets the value for the SO_BINDTODEVICE option on this socket

This value gets the socket binded device’s interface name.

Source

pub fn bind_device(&self, interface: Option<&[u8]>) -> Result<()>

Available on (Android or Fuchsia or Linux) and crate feature net only.

Sets the value for the SO_BINDTODEVICE option on this socket

If 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_INET sockets.

If interface is None or an empty string it removes the binding.

Source

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

Available on crate feature net only.

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(())
}
Source

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

Available on crate feature net only.

Returns the value of the SO_ERROR option.

Source

pub fn bind(&self, addr: SocketAddr) -> Result<()>

Available on crate feature net only.

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)?;

    Ok(())
}
Source

pub async fn connect(self, addr: SocketAddr) -> Result<TcpStream>

Available on crate feature net only.

Establishes a TCP connection with a peer at the specified socket address.

The TcpSocket is consumed. Once the connection is established, a connected TcpStream is 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?;

    Ok(())
}
Source

pub fn listen(self, backlog: u32) -> Result<TcpListener>

Available on crate feature net only.

Converts the socket into a TcpListener.

backlog defines the maximum number of pending connections are queued by the operating system at any given time. Connection are removed from the queue with TcpListener::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)?;

    Ok(())
}
Source

pub fn from_std_stream(std_stream: TcpStream) -> TcpSocket

Available on crate feature net only.

Converts a std::net::TcpStream into a TcpSocket. The provided socket must not have been connected prior to calling this function. This function is typically used together with crates such as socket2 to configure socket options that are not available on TcpSocket.

§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 tokio::net::TcpSocket;
use socket2::{Domain, Socket, Type};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let socket2_socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
    socket2_socket.set_nonblocking(true)?;

    let socket = TcpSocket::from_std_stream(socket2_socket.into());

    Ok(())
}

Trait Implementations§

Source§

impl AsFd for TcpSocket

Available on crate feature net and Unix only.
Source§

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

Borrows the file descriptor. Read more
Source§

impl AsRawFd for TcpSocket

Available on crate feature net and Unix only.
Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl AsRawSocket for TcpSocket

Available on crate feature net and Windows only.
Source§

fn as_raw_socket(&self) -> RawSocket

Available on docsrs and Unix and (crate features net or fs) only.
Source§

impl AsSocket for TcpSocket

Available on crate feature net and Windows only.
Source§

fn as_socket(&self) -> BorrowedSocket<'_>

Available on docsrs and Unix and (crate features net or fs) only.
Source§

impl Debug for TcpSocket

Available on crate feature net only.
Source§

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

Formats the value using the given formatter. Read more
Source§

impl FromRawFd for TcpSocket

Available on crate feature net and Unix only.
Source§

unsafe fn from_raw_fd(fd: RawFd) -> TcpSocket

Converts a RawFd to a TcpSocket.

§Notes

The caller is responsible for ensuring that the socket is in non-blocking mode.

Source§

impl FromRawSocket for TcpSocket

Available on crate feature net and Windows only.
Source§

unsafe fn from_raw_socket(socket: RawSocket) -> TcpSocket

Available on docsrs and Unix and (crate features net or fs) only.

Converts a RawSocket to a TcpStream.

§Notes

The caller is responsible for ensuring that the socket is in non-blocking mode.

Source§

impl IntoRawFd for TcpSocket

Available on crate feature net and Unix only.
Source§

fn into_raw_fd(self) -> RawFd

Consumes this object, returning the raw underlying file descriptor. Read more
Source§

impl IntoRawSocket for TcpSocket

Available on crate feature net and Windows only.
Source§

fn into_raw_socket(self) -> RawSocket

Available on docsrs and Unix and (crate features net or fs) only.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more