std-method
TcpStream::local_addr and peer_addr
Inspect the local and remote addresses of a connection. Both endpoints in this fixture are loopback; their roles are reversed when viewed from the opposite stream. Expected stdout (not executed): true true Common mistake: Treating an endpoint IP or port as authenticated user identity.
Formal Syntax & Structure
rust syntaxrust
stream.local_addr(); stream.peer_addr()Working Example
Example Snippetrust
fn main() { use std::{net::{Ipv4Addr, TcpListener, TcpStream}, time::Duration}; let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let mut client = TcpStream::connect_timeout(&listener.local_addr().unwrap(), Duration::from_secs(2)).unwrap(); let (mut server, _) = listener.accept().unwrap(); for s in [&client, &server] { s.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); s.set_write_timeout(Some(Duration::from_secs(2))).unwrap(); } println!("{} {}", client.peer_addr().unwrap() == server.local_addr().unwrap(), server.peer_addr().unwrap() == client.local_addr().unwrap());}