diff --git a/sqlx-core/src/net/socket/mod.rs b/sqlx-core/src/net/socket/mod.rs index cad4d576..f11c10de 100644 --- a/sqlx-core/src/net/socket/mod.rs +++ b/sqlx-core/src/net/socket/mod.rs @@ -205,15 +205,28 @@ pub async fn connect_tcp( 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::::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::::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"))]