Tokio::net TcpStream 3-5 sec cost for failed connection?

I am trying to write a simple network scanner to find hosts with a specific open port using Tokio::net::TcpStream::connect. Open connections are really fast, but a closed/blocked port results in a delay of 3-5 seconds. So scanning 254 ports takes about 130 seconds on my pc multi-threaded. I can't find the reason, I was hoping someone here might be able to lend some insight into the reason and maybe a solution to speed it up.

You likely are right. I'm obviously still learning and trying to figure things out. This is the code that I have working. I know it's ugly and I'm wide open to criticisms and suggestions. I'm still new and trying to learn idiomatic rust.

println!("starting");
let mut stream_vec = Vec::new();
for i in 1..254{
    let ip = "10.0.3.";
    let jh = tokio::spawn(
        async move{
            let f = format!("{}{}:{}",ip.clone(),i,"80");
            let ts = TcpStream::connect(f.clone()).await;
            match ts{
                Ok(a)=>{
                    println!("{:?}",&a.peer_addr());
                },
                Err(e)=>{
                    println!("{}:{}",&f,e);
                }
            }
    });
    stream_vec.push(jh);
}
for handle in stream_vec{
    let a = handle.await;
    match a{
        Ok(res)=>{
        },
        Err(e)=>{println!("JoinErrer:{}",e);}
    };
}
println!("Done");
}

This sounds like a connection timeout. Connection fails immediately only if the host actively responds to deny the request. If the host does nothing, then connect can't know if the port is closed, or if the port is open, but the host is slow or a packet has been lost.

You could add connection timeouts. Any future can be timed out by wrapping it in tokio::time::timeout.

Most of the slow errors are no route to host errors. Those are network errors from the host OS, so it seems not to be the library? It still seems too long, but I guess I'll need to use the timeout.

I didn't see ARP requests in the library. Did I just miss them?

Tokio's socket is documented as " This calls the connect(2) operating-system function.", so I assume the TcpStream is also only a very high-level wrapper, so it doesn't do ARP or anything like that by itself.

Yes, all that the TcpStream type in Tokio does is set the socket to non-blocking mode, perform the usual syscalls, and when they return WouldBlock, register them with epoll. It doesn't do anything fancy.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.