30

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()));
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user3746744
  • 433
  • 1
  • 4
  • 10

2 Answers2

42

from_str was renamed to parse and is now a method you can call 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'd like to be able to resolve DNS entries to IPv{4,6} addresses, you may want to 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 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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
10

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 of ToSocketAddr trait:

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

It means that you can just pass a string to connect() without any conversions:

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

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

Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296
  • The string is a host:port combo from stdin. The address would change each time. I'm quite sure it needs to be converted. – user3746744 Feb 02 '15 at 14:58
  • Sorry, but I don't understand what you mean. You don't need to call `to_socket_addr()` manually when you just want to connect to something. And what do you mean about address changing each time? – Vladimir Matveev Feb 02 '15 at 15:02
  • @vladimir-matveev ToSocketAddr expects (among other things) Name:Port or Address:Port when converting strings "www.example.com".to_socketaddr "192.168.0.1:80".to_socketaddr "192.168.0.1:80".to_socketaddr – HerbM Apr 05 '21 at 09:31