std-method

TcpStream::connect_timeout

Set a connection-attempt budget for a single already-resolved address. It is not a DNS or end-to-end request timeout. A zero timeout is invalid. Expected stdout (not executed): true true Common mistake: Applying one connection timeout and claiming the entire request is bounded.

Formal Syntax & Structure

rust syntaxrust
TcpStream::connect_timeout(&addr, timeout) -> io::Result<TcpStream>

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 addr = listener.local_addr().unwrap();    println!("{}", TcpStream::connect_timeout(&addr, Duration::ZERO).is_err());    let client = TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();    let _server = listener.accept().unwrap();    println!("{}", client.peer_addr().unwrap() == addr);}
Rust Reference