std-method

TcpListener::accept: obtain peer endpoint

Accept returns a connected stream and the address of the remote endpoint. The listener remains available for more connections. A blocking accept may wait indefinitely unless the surrounding design limits it. Expected stdout (not executed): true Common mistake: Confusing the listener address with the accepted peer address.

Formal Syntax & Structure

rust syntaxrust
listener.accept() -> io::Result<(TcpStream, SocketAddr)>

Working Example

Example Snippetrust
fn main() {    use std::net::{Ipv4Addr, TcpListener};    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();    use std::{net::TcpStream, time::Duration};    let client = TcpStream::connect_timeout(&listener.local_addr().unwrap(), Duration::from_secs(2)).unwrap();    let (_server, peer) = listener.accept().unwrap();    println!("{}", peer == client.local_addr().unwrap());}
Rust Reference