use async_trait::async_trait;
use std::net::IpAddr;
use tokio::runtime::Handle;
use trust_dns_resolver::{error::ResolveErrorKind, TokioAsyncResolver};
#[async_trait]
pub trait Lookup {
async fn lookup(&self, ip: IpAddr) -> Option<String>;
}
pub struct Resolver(TokioAsyncResolver);
impl Resolver {
pub async fn new(runtime: Handle) -> Result<Self, failure::Error> {
let resolver = TokioAsyncResolver::from_system_conf(runtime).await?;
Ok(Self(resolver))
}
}
#[async_trait]
impl Lookup for Resolver {
async fn lookup(&self, ip: IpAddr) -> Option<String> {
let lookup_future = self.0.reverse_lookup(ip);
match lookup_future.await {
Ok(names) => {
names.into_iter().next().map(|name| name.to_string())
}
Err(e) => match e.kind() {
ResolveErrorKind::NoRecordsFound { .. } => Some(ip.to_string()),
_ => None,
},
}
}
}