Convert String to SocketAddr

后端 未结 2 1240
不知归路
不知归路 2021-02-12 22:50

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 ca

2条回答
  •  生来不讨喜
    2021-02-12 23:05

    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(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.

提交回复
热议问题