Skip to main content

tokio_websockets/
resolver.rs

1//! Abstractions over DNS resolvers.
2
3use std::{future::Future, net::SocketAddr};
4
5use crate::Error;
6
7/// Trait for a DNS resolver to resolve hostnames and ports to IP addresses.
8pub trait Resolver: Send {
9    /// Resolve a hostname and port to an IP address, asynchronously.
10    fn resolve(
11        &self,
12        host: &str,
13        port: u16,
14    ) -> impl Future<Output = Result<SocketAddr, Error>> + Send;
15}
16
17/// A [`Resolver`] that uses the blocking `getaddrinfo` syscall in the tokio
18/// threadpool.
19pub struct Gai;
20
21impl Resolver for Gai {
22    async fn resolve(&self, host: &str, port: u16) -> Result<SocketAddr, Error> {
23        let host = host.to_owned();
24
25        tokio::net::lookup_host((host, port))
26            .await
27            .map_err(|_| Error::CannotResolveHost)?
28            .next()
29            .ok_or(Error::CannotResolveHost)
30    }
31}