dns: provide lookup_host function (#1870)

`ToSocketAddrs` is a sealed trait pending changes in Rust that will allow
defining async trait fns. Until then, `net::lookup_host` is provided as a way
to convert a `T: ToSocketAddrs` into `SocketAddr`s.
This commit is contained in:
David Barsky
2019-12-21 08:30:00 -08:00
committed by Carl Lerche
parent 3dcd76a38f
commit de5ec6e1bc
3 changed files with 79 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
cfg_dns! {
use crate::net::addr::ToSocketAddrs;
use std::io;
use std::net::SocketAddr;
/// Performs a DNS resolution.
///
/// The returned iterator may not actually yield any values depending on the
/// outcome of any resolution performed.
///
/// This API is not intended to cover all DNS use cases. Anything beyond the
/// basic use case should be done with a specialized library.
///
/// # Examples
///
/// To resolve a DNS entry:
///
/// ```no_run
/// use tokio::net;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// for addr in net::lookup_host("localhost:3000").await? {
/// println!("socket address is {}", addr);
/// }
///
/// Ok(())
/// }
/// ```
pub async fn lookup_host<T>(host: T) -> io::Result<impl Iterator<Item = SocketAddr>>
where
T: ToSocketAddrs
{
host.to_socket_addrs().await
}
}
+5
View File
@@ -25,6 +25,11 @@
mod addr;
pub use addr::ToSocketAddrs;
cfg_dns! {
mod lookup_host;
pub use lookup_host::lookup_host;
}
cfg_tcp! {
pub mod tcp;
pub use tcp::listener::TcpListener;
+36
View File
@@ -0,0 +1,36 @@
use tokio::net;
use tokio_test::assert_ok;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
#[tokio::test]
async fn lookup_socket_addr() {
let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
let actual = assert_ok!(net::lookup_host(addr).await).collect::<Vec<_>>();
assert_eq!(vec![addr], actual);
}
#[tokio::test]
async fn lookup_str_socket_addr() {
let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
let actual = assert_ok!(net::lookup_host("127.0.0.1:8000").await).collect::<Vec<_>>();
assert_eq!(vec![addr], actual);
}
#[tokio::test]
async fn resolve_dns() -> io::Result<()> {
let mut hosts = net::lookup_host("localhost:3000").await?;
let host = hosts.next().unwrap();
let expected = if host.is_ipv4() {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 3000)
} else {
SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 3000)
};
assert_eq!(host, expected);
Ok(())
}