Convert string to SocketAddr

In versions of Rust prior to 1.0, I was able to use from_str() to convert String to SocketAddr , but this function no longer exists. How to do it 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())); 
+8
source share
2 answers

from_str been renamed for parse and is now a method that can be called on strings:

 use std::net::SocketAddr; fn main() { let server_details = "127.0.0.1:80"; let server: SocketAddr = server_details .parse() .expect("Unable to parse socket address"); println!("{:?}", server); } 

If you want to allow DNS records by IPv {4,6} addresses, you can use ToSocketAddrs :

 use std::net::{TcpStream, ToSocketAddrs}; fn main() { let server_details = "stackoverflow.com:80"; let server: Vec<_> = server_details .to_socket_addrs() .expect("Unable to resolve domain") .collect(); println!("{:?}", server); // Even easier, if you want to connect right away: TcpStream::connect(server_details).expect("Unable to connect to server"); } 

to_socket_addrs returns an iterator, since one DNS record can expand to several IP addresses! Please note that this code will not work on the playground, as network access is disabled there; you will need to try this on the spot.

+11
source

I will explain the answer “if you want to connect right away” in Shepmaster's answer.

Note that you really don't need to convert the string to SocketAddr in SocketAddr to connect to something. TcpStream::connect() and other functions that accept addresses are defined to receive an instance of ToSocketAddr :

 fn connect<T: ToSocketAddr>(addr: T) -> TcpStream { ... } 

This means that you can just pass the connect() string without any conversions:

 TcpStream::connect("stackoverflow.com:80") 

Moreover, it is better not to translate the string into SocketAddr in advance, because domain names can resolve multiple addresses, and TcpStream has special logic to handle this.

+3
source

Source: https://habr.com/ru/post/1212342/


All Articles