I noticed that whenever I iterate over the socket addresses via a ToSocketAddrs iterator that involves turning names into IP addresses (even "localhost"), I see every socket address three times. Is this intentional? Is this a bug? Where does the redundancy come in? Is it part of the Rust stdlib implementation or does my OS (GNU/Linux) already give me this redundancy?
Try for yourself:
use std::io;
use std::net::ToSocketAddrs;
fn foo<S: ToSocketAddrs>(s: S) -> Result<(), io::Error> {
for (idx, sockaddr) in (1..).zip(try!(s.to_socket_addrs())) {
println!("{}. {}", idx, sockaddr);
}
Ok(())
}
fn main() {
match foo("localhost:80") {
Err(x) => println!("{}", x),
_ => (),
}
}
(It won't work in playpen due to some OS API calls being blocked)
This is normal behaviour. to_socket_addrs internally just calls getaddrinfo without hints, which in turn means that it will return resolved addresses for each socket type (SOCK_STREAM, SOCK_DGRAM, SOCK_RAW). ToSocketAddrs later drops all other information, so Rust could be a bit smarter here and set a SOCK_STREAM hint.