issue #2821 Update error handling logic when opening a TCP connection (#2822)

This commit updates the error handling logic in the `connect_tcp` function. Previously, the function would panic if the hostname did not resolve to at least one address.

The updated logic attempts to establish a TCP connection for each address that the hostname resolves to. If it fails to connect to any of the addresses, it will return the last encountered error. If the hostname doesn't resolve to any addresses, the function returns a custom error message stating "Hostname did not resolve to any addresses".
This commit is contained in:
Anup Jadhav 2023-10-19 22:55:45 +01:00 committed by GitHub
parent 00b077ab14
commit 49ccc7ca32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -205,15 +205,28 @@ pub async fn connect_tcp<Ws: WithSocket>(
use async_std::net::ToSocketAddrs;
use std::net::TcpStream;
let socket_addr = (host, port)
.to_socket_addrs()
.await?
.next()
.expect("BUG: to_socket_addrs() should have returned at least one result");
let mut last_err = None;
let stream = Async::<TcpStream>::connect(socket_addr).await?;
// Loop through all the Socket Addresses that the hostname resolves to
for socket_addr in (host, port).to_socket_addrs().await? {
match Async::<TcpStream>::connect(socket_addr).await {
Ok(stream) => return Ok(with_socket.with_socket(stream)),
Err(e) => last_err = Some(e),
}
}
return Ok(with_socket.with_socket(stream));
// If we reach this point, it means we failed to connect to any of the addresses.
// Return the last error we encountered, or a custom error if the hostname didn't resolve to any address.
match last_err {
Some(err) => return Err(err.into()),
None => {
return Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
"Hostname did not resolve to any addresses",
)
.into())
}
}
}
#[cfg(not(feature = "_rt-async-std"))]