Convert String to SocketAddr

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)