Hostname resolution without port


I'm playing around with socket addresses, and I've found the trait named ToSocketAddrs. Some implementations of this will take an &str like "localhost" and resolve it using lower level functions like Linux' getaddrinfo, or similar on other systems. But this requires you to specify a port up front, which does not seem to be strictly required, nor even supported by the lower level functions in question.

Is there any reason why such a trait does not exist for IpAddr, so that you could resolve the hostname by itself? Or maybe I'm just missing something?

Well, an IpAddr is the output of a hostname lookup, so if you have an IpAddr you don't need to do the lookup step at all.

Otherwise, I think the common thing is to just pass the port number 0.

1 Like

I'm not entirely sure what you mean.

The scenario is that you have an &str like "localhost" or "myserver", which is defined in /etc/hosts or something similar, and then you want to ask the system to resolve it into an IpAddr. But there doesn't seem to be any functionality to do that, except for the trait ToSocketAddr, which declares the function to_socket_addrs() that resolves a hostname+port pair into an iterator of ip+port pairs in the form of SocketAddrs.

Sure, you could pass 0 as a port, and then extract the IpAddr from the resulting SocketAddr, but it feels really unnecessary. Especially considering that the port shouldn't have any effect on the resolution (AFAIK).

Unfortunately the standard library team decided to resolve hostnames to socket addresses (with the port number) and not plain IP addresses. You can see part of the discussion below:

If you want an alternative, you can either use a dummy port number or if you're willing to add an extra dependency, the dns-lookup crate does what you want.

let ips: Vec<std::net::IpAddr> = dns_lookup::lookup_host("localhost").unwrap();

I guess it could make sense if you were automatically checking SRV records, but that does seem kinda weird.

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.