Struct TcpListener

pub struct TcpListener(pub(in ::net::tcp) TcpListener);

A TCP socket server, listening for connections.

After creating a TcpListener by binding it to a socket address, it listens for incoming TCP connections. These can be accepted by calling accept or by iterating over the Incoming iterator returned by [incoming]TcpListener::incoming.

The socket will be closed when the value is dropped.

The Transmission Control Protocol is specified in IETF RFC 793.

Examples

use std::net::{TcpListener, TcpStream};

fn handle_client(stream: TcpStream) {
    // ...
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;

    // accept connections and process them serially
    for stream in listener.incoming() {
        handle_client(stream?);
    }
    Ok(())
}

Fields

0: TcpListener

Implementations

impl TcpListener

fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpListener>

Creates a new TcpListener which will be bound to the specified address.

The returned listener is ready for accepting connections.

Binding with a port number of 0 will request that the OS assigns a port to this listener. The port allocated can be queried via the TcpListener::local_addr method.

The address type can be any implementor of ToSocketAddrs trait. See its documentation for concrete examples.

If addr yields multiple addresses, bind will be attempted with each of the addresses until one succeeds and returns the listener. If none of the addresses succeed in creating a listener, the error returned from the last attempt (the last address) is returned.

Examples

Creates a TCP listener bound to 127.0.0.1:80:

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();

Creates a TCP listener bound to 127.0.0.1:80. If that fails, create a TCP listener bound to 127.0.0.1:443:

use std::net::{SocketAddr, TcpListener};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 80)),
    SocketAddr::from(([127, 0, 0, 1], 443)),
];
let listener = TcpListener::bind(&addrs[..]).unwrap();

Creates a TCP listener bound to a port assigned by the operating system at 127.0.0.1.

use std::net::TcpListener;

let socket = TcpListener::bind("127.0.0.1:0").unwrap();
fn local_addr(&self) -> Result<SocketAddr>

Returns the local socket address of this listener.

Examples

use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
assert_eq!(listener.local_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
fn try_clone(&self) -> Result<TcpListener>

Creates a new independently owned handle to the underlying socket.

The returned TcpListener is a reference to the same socket that this object references. Both handles can be used to accept incoming connections and options set on one listener will affect the other.

Examples

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let listener_clone = listener.try_clone().unwrap();
fn accept(&self) -> Result<(TcpStream, SocketAddr)>

Accept a new incoming connection from this listener.

This function will block the calling thread until a new TCP connection is established. When established, the corresponding TcpStream and the remote peer's address will be returned.

Errors

Some errors this function returns do not indicate a problem with the listener itself, and a program serving a long-lived listener will usually want to handle them and keep accepting connections rather than treat them as fatal. These include, but are not limited to:

  • An error specific to a single incoming connection that failed before it could be accepted, such as one aborted by the peer (ConnectionAborted). A later call may succeed immediately.
  • An error from reaching the per-process or system-wide open file descriptor limit. The call can be retried once other file descriptors have been closed, typically after a short delay.
  • An error from failing to allocate memory while accepting a connection (OutOfMemory).

Which errors can occur is platform-specific. On Unix, Interrupted errors are retried internally rather than being returned.

Examples

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
match listener.accept() {
    Ok((_socket, addr)) => println!("new client: {addr:?}"),
    Err(e) => println!("couldn't get client: {e:?}"),
}
fn incoming(&self) -> Incoming<'_>

Returns an iterator over the connections being received on this listener.

The returned iterator will never return None and will also not yield the peer's SocketAddr structure. Iterating over it is equivalent to calling TcpListener::accept in a loop.

Errors

Each connection yielded by the iterator can fail for the same reasons as TcpListener::accept; see its documentation for details.

Examples

use std::net::{TcpListener, TcpStream};

fn handle_connection(stream: TcpStream) {
   //...
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                handle_connection(stream);
            }
            Err(e) => { /* connection failed */ }
        }
    }
    Ok(())
}
fn into_incoming(self) -> IntoIncoming

Turn this into an iterator over the connections being received on this listener.

The returned iterator will never return None and will also not yield the peer's SocketAddr structure. Iterating over it is equivalent to calling TcpListener::accept in a loop.

Errors

Each connection yielded by the iterator can fail for the same reasons as TcpListener::accept; see its documentation for details.

Examples

#![feature(tcplistener_into_incoming)]
use std::net::{TcpListener, TcpStream};

fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
    let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
    listener.into_incoming()
        .filter_map(Result::ok) /* Ignore failed connections */
}

fn main() -> std::io::Result<()> {
    for stream in listen_on(80) {
        /* handle the connection here */
    }
    Ok(())
}
fn set_ttl(&self, ttl: u32) -> Result<()>

Sets the value for the IP_TTL option on this socket.

This value sets the time-to-live field that is used in every packet sent from this socket.

Examples

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.set_ttl(100).expect("set_ttl should succeed");
fn ttl(&self) -> Result<u32>

Gets the value of the IP_TTL option for this socket.

For more information about this option, see TcpListener::set_ttl.

Examples

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.set_ttl(100).expect("set_ttl should succeed");
assert_eq!(listener.ttl().unwrap_or(0), 100);
fn set_only_v6(&self, only_v6: bool) -> Result<()>
fn only_v6(&self) -> Result<bool>
fn take_error(&self) -> Result<Option<Error>>

Gets the value of the SO_ERROR option 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.

Examples

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.take_error().expect("`take_error` should succeed");
fn set_nonblocking(&self, nonblocking: bool) -> Result<()>

Moves this TCP stream into or out of nonblocking mode.

This will result in the accept operation becoming nonblocking, i.e., immediately returning from their calls. If the IO operation is successful, Ok is returned and no further action is required. If the IO operation could not be completed and needs to be retried, an error with kind io::ErrorKind::WouldBlock is returned.

On most Unix platforms, calling this method corresponds to calling ioctl FIONBIO. On Windows, calling this method corresponds to calling ioctlsocket FIONBIO.

Examples

Bind a TCP listener to an address, listen for connections, and read bytes in nonblocking mode:

use std::io;
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
listener.set_nonblocking(true).expect("set_nonblocking should succeed");

# fn wait_for_fd() { unimplemented!() }
# fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
for stream in listener.incoming() {
    match stream {
        Ok(s) => {
            // do something with the TcpStream
            handle_connection(s);
        }
        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
            // wait until network socket is ready, typically implemented
            // via platform-specific APIs such as epoll or IOCP
            wait_for_fd();
            continue;
        }
        Err(e) => panic!("encountered IO error: {e}"),
    }
}

Trait Implementations

impl AsFd for TcpListener

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

impl AsInner<TcpListener> for TcpListener

fn as_inner(&self) -> &TcpListener

impl AsRawFd for TcpListener

fn as_raw_fd(&self) -> RawFd

impl AsRawSocket for TcpListener

fn as_raw_socket(&self) -> RawSocket

impl AsSocket for TcpListener

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

impl Debug for TcpListener

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

impl From<OwnedFd> for TcpListener

fn from(owned_fd: OwnedFd) -> Self

impl From<OwnedSocket> for TcpListener

fn from(owned: OwnedSocket) -> Self

impl FromInner<TcpListener> for TcpListener

fn from_inner(inner: TcpListener) -> TcpListener

impl FromRawFd for TcpListener

unsafe fn from_raw_fd(fd: RawFd) -> TcpListener

impl FromRawSocket for TcpListener

unsafe fn from_raw_socket(sock: RawSocket) -> TcpListener

impl IntoInner<TcpListener> for TcpListener

fn into_inner(self) -> TcpListener

impl IntoRawFd for TcpListener

fn into_raw_fd(self) -> RawFd

impl IntoRawSocket for TcpListener

fn into_raw_socket(self) -> RawSocket

Auto Trait Implementations

impl Freeze for TcpListener

impl RefUnwindSafe for TcpListener

impl Send for TcpListener

impl Sync for TcpListener

impl Unpin for TcpListener

impl UnsafeUnpin for TcpListener

impl UnwindSafe for TcpListener

Blanket Implementations

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

fn type_id(&self) -> TypeId

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

fn borrow(&self) -> &T

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

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

impl<T> From<T> for TcpListener

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> SizeHint for TcpListener where T: ?Sized,

fn lower_bound(&self) -> usize
fn upper_bound(&self) -> Option<usize>

impl<T> SizedTypeProperties for TcpListener

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

fn into(self) -> U

Calls U::from(self).

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

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

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

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

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