Rust: TcpStream bind before connect

Created on 9 Jan 2020  路  4Comments  路  Source: rust-lang/rust

We now have TcpStream::connect and TcpStream::connect_timeout to create a TcpStream.

But there is no option for us to do before calling connect(), in particular, bind() to the source address.

Proposal:

fn connect_with<A>(bind_addr: &SocketAddr, A: addr) -> io::Result<TcpStream>
    where A: ToSocketAddrs
{
    // ...
}

fn connect_with_timeout(bind_addr: &SocketAddr,
                        addr: &SocketAddr,
                        timeout: Duration)
                        -> io::Result<TcpStream>
{
    // ...
}
C-feature-request T-libs

Most helpful comment

connect_with

It's generally a bad idea to cram socket setup into a single method since there are a bunch of configuration APIs you may want to call on an unconnected socket, bind is just one of them.

Instead it would be better to have a new(address_family) constructor which corresponds to the socket() syscall and creates an unconnected socket. Then one can bind it, set socket options/fcntls and finally connect.

Or perhaps a TcpSocket that acts as builder and can either be connected to create a TcpStream or use listen to create a TcpListener.

All 4 comments

@jonas-schievink I am Ok to send a PR for this.

Proposed names:

  1. connect_with
  2. connect_from
  3. connect_by
  4. bind_connect

Feel free to do that. The libs team has to decide whether to take it. IMO connect_from is the clearest name.

connect_with

It's generally a bad idea to cram socket setup into a single method since there are a bunch of configuration APIs you may want to call on an unconnected socket, bind is just one of them.

Instead it would be better to have a new(address_family) constructor which corresponds to the socket() syscall and creates an unconnected socket. Then one can bind it, set socket options/fcntls and finally connect.

Or perhaps a TcpSocket that acts as builder and can either be connected to create a TcpStream or use listen to create a TcpListener.

Or perhaps a TcpSocket that acts as builder and can either be connected to create a TcpStream or use listen to create a TcpListener.

Yes, TcpSocket is the best solution.

Was this page helpful?
0 / 5 - 0 ratings