In versions of Rust before 1.0, I was able to use from_str()
to convert a String
to SocketAddr
, but that function no longer exists. How can I do this in Rust 1.0.?
let server_details = reader.read_line().ok().expect("Something went wrong").as_slice().trim();
let server: SocketAddr = from_str(server_details);
let mut s = BufferedStream::new((TcpStream::connect(server).unwrap()));
from_str
was renamed toparse
and is now a method you can call on strings:If you'd like to be able to resolve DNS entries to IPv{4,6} addresses, you may want to use
ToSocketAddrs
:to_socket_addrs
returns an iterator as a single DNS entry can expand to multiple IP addresses! Note that this code won't work in the playground as network access is disabled there; you'll need to try it out locally.I'll expand on "if you want to connect right away" comment in Shepmaster's answer.
Note that you don't really need to convert a string to a
SocketAddr
in advance in order to connect to something.TcpStream::connect()
and other functions which take addresses are defined to accept an instance ofToSocketAddr
trait:It means that you can just pass a string to
connect()
without any conversions:Moreover, it is better not to convert the string to the
SocketAddr
in advance because domain names can resolve to multiple addresses, andTcpStream
has special logic to handle this.