spicavigo
spicavigo

Reputation: 4224

How do I set connect timeout on TcpStream

I am trying to connect to a server which is unreachable using the following code:

println!("Connecting");
TcpStream::connect(s).unwrap();
println!("Connected");

When I run the code, it gets stuck on second line.

Output:

Connecting

Upvotes: 8

Views: 10776

Answers (4)

Aiyion.Prime
Aiyion.Prime

Reputation: 1042

greetings from 2020.

In the meantime the answer changed, it's no longer "can't be done easily" but is:

TcpStream::connect_timeout()

https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.connect_timeout

Upvotes: 17

user10146018
user10146018

Reputation:

If you are using async rust with tokio then you can use this:-

const CONNECTION_TIME: u64 = 100;

...

let (socket, _response) = match tokio::time::timeout(
     Duration::from_secs(CONNECTION_TIME),
     tokio::net::TcpStream::connect("127.0.0.1:8080")
 )
 .await
 {
     Ok(ok) => ok,
     Err(e) => panic!(format!("timeout while connecting to server : {}", e)),
 }
 .expect("Error while connecting to server")

Upvotes: 14

Yohaï-Eliel Berreby
Yohaï-Eliel Berreby

Reputation: 1175

There is no easy, standard way to do this, so I did it by porting this answer to Rust using the nix crate, with a minor change: setting the socket back to blocking once the connection has been established, so that it can be used with Rust's std I/O, and of course wrapping it back in a std::net::TcpStream.

Here is the repo: https://github.com/filsmick/rust-tcp-connection-timeout

From src/lib.rs:

pub fn tcp_connect_with_timeout(socket_addr: std::net::SocketAddr, timeout: Duration) -> Result<TcpStream, ConnectionError> {
  // Create a socket file descriptor.
  let socket_fd = try!(nix::sys::socket::socket(
    nix::sys::socket::AddressFamily::Inet,
    nix::sys::socket::SockType::Stream,
    nix::sys::socket::SockFlag::empty()
  ));

  // Set the socket to non-blocking mode so we can `select()` on it.
  try!(nix::fcntl::fcntl(
    socket_fd,
    nix::fcntl::FcntlArg::F_SETFL(nix::fcntl::O_NONBLOCK)
  ));

  let connection_result = nix::sys::socket::connect(
    socket_fd,
    &(nix::sys::socket::SockAddr::Inet(nix::sys::socket::InetAddr::from_std(&socket_addr)))
  );

  match connection_result {
    Ok(_) => (),
    Err(e) => {
      match e {
        nix::Error::Sys(errno) => {
          match errno {
            nix::errno::Errno::EINPROGRESS => (), // socket is non-blocking so an EINPROGRESS is to be expected
            _ => return Err(ConnectionError::from(e))
          }
        }
        nix::Error::InvalidPath => unreachable!() //
      }
    }
  }

  let mut timeout_timeval = nix::sys::time::TimeVal {
    tv_sec: timeout.as_secs() as i64,
    tv_usec: timeout.subsec_nanos() as i32
  };

  // Create a new fd_set monitoring our socket file descriptor.
  let mut fdset = nix::sys::select::FdSet::new();
  fdset.insert(socket_fd);

  // `select()` on it, will return when the connection succeeds or times out.
  let select_res = try!(nix::sys::select::select(
    socket_fd + 1,
    None,
    Some(&mut fdset),
    None,
    &mut timeout_timeval
  ));

  // This it what fails if `addr` is unreachable.
  if select_res != 1 {
    println!("select return value: {}", select_res);
    return Err(ConnectionError::SelectError);
  }

  // Make sure the socket encountered no error.
  let socket_error_code = try!(nix::sys::socket::getsockopt(
    socket_fd,
    nix::sys::socket::sockopt::SocketError
  ));

  if socket_error_code != 0 {
    return Err(ConnectionError::SocketError(socket_error_code));
  }

  // Set the socket back to blocking mode so it can be used with std's I/O facilities.
  try!(nix::fcntl::fcntl(
    socket_fd,
    nix::fcntl::FcntlArg::F_SETFL(nix::fcntl::OFlag::empty())
  ));

  // Wrap it in a TcpStream and return that stream.
  Ok(
    unsafe { TcpStream::from_raw_fd(socket_fd) }
  )
}

ConnectionError is defined in error.rs, but you can ignore it if you wish by unwrapping instead of using try!.

There's a catch, though: select isn't yet implemented in the main nix repo at the time of writing but there is a pending Pull Request, so you'll have to depend on a fork in the meantime (it shouldn't take long to merge, though):

[dependencies]
nix = { git = "https://github.com/utkarshkukreti/nix-rust.git", branch = "add-sys-select" }

Upvotes: 2

Chris Morgan
Chris Morgan

Reputation: 90742

It is not at present possible to alter the timeout on making a TCP connection. The network stacks will have their own default settings, which may vary from OS to OS; I believe that one minute is a typical timeout.

Upvotes: 0

Related Questions