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?
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();
assert!(ips.contains(&"127.0.0.1".parse().unwrap()));