Cannot get IP Address of a Hostname

I want to get the IP Address of a passed hostname like this:

pub fn get_ip(host: &str) -> Result<String, error_handler::ExtractCodeError> {
    let mut s: String = String::new();

    if let Some(ip) = host.parse::<IpAddr>().ok().or_else(||
        host.strip_prefix("[")?
            .strip_suffix("]")?
            .parse::<IpAddr>().ok()
    ) {
        s = ip.to_string();
    } else {
        for i in dns_lookup::lookup_host(host).unwrap() {
            match i {
                IpAddr::V4(ip4) => s = ip4.to_string(),
                IpAddr::V6(ip6) => error!("IPv6 Addresses are not supported, {}...", ip6.to_string())
            }
        }
    }
    info!("IP Address {} of domain: {}", s, host);

    Ok(s)
}

The host string literal is correct but I always get

thread '<unnamed>' panicked at src/service/ip_domain_service.rs:71:48:
called `Result::unwrap()` on an `Err` value: Custom { kind: Other, error: "failed to lookup address information: Name or service not known" }

Is there anything I miss? I tried it with example.com and washingtonpost.com

I don't know the dns_lookup library you are using, but the error seems to have originated from the operating system resolver.

what os are you using? how is your system's dns configured?

for a quick check, what's the result if you use ToSocketAddrs in std? see

1 Like

I fixed it. There was a problem with the host. The double quotes were still in the string literal. I had to remove them first.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.