async-std icon indicating copy to clipboard operation
async-std copied to clipboard

Provide a way to configure sockets

Open Deniskore opened this issue 5 years ago • 6 comments

Consider providing additional methods to configure socket

  • SO_REUSEADDR
  • SO_LINGER

I refrain from using async-std due to their absence. You can check these options in socket2 crate.

Deniskore avatar Jan 14 '20 15:01 Deniskore

@Deniskore you can convert from socket2 types to std types, and in turn we provide conversions from std types to async_std types. async_std will ensure the non blocking flags are set correctly when converting.

I agree I'd love to see BSD socket support as part of std/async_std in the long term, but at least this should help get you unblocked!

yoshuawuyts avatar Jan 14 '20 16:01 yoshuawuyts

@yoshuawuyts Could you please provide a code snippet for these conversions?

        let socket = socket2::Socket::new(
            socket2::Domain::ipv4(),
            socket2::Type::stream(),
            Some(socket2::Protocol::tcp()),
        )?;
        socket.set_reuse_address(true)?;
        socket.set_linger(Some(Duration::from_secs(0)))?;
        socket.bind(&"0.0.0.0:0".parse::<SocketAddr>()?.into())?;
        // Convert and setup...

Deniskore avatar Jan 14 '20 16:01 Deniskore

@Deniskore the following APIs are relevant here (for e.g. a TcpListener):

  • https://docs.rs/socket2/0.3.11/socket2/struct.Socket.html#method.into_tcp_listener
  • https://docs.rs/async-std/1.4.0/async_std/net/struct.TcpListener.html#impl-From%3CTcpListener%3E

Example

I haven't run the code, but this should get the general idea across:

        let socket = socket2::Socket::new(
            socket2::Domain::ipv4(),
            socket2::Type::stream(),
            Some(socket2::Protocol::tcp()),
        )?;
        socket.set_reuse_address(true)?;
        socket.set_linger(Some(Duration::from_secs(0)))?;

        let socket = socket.into_tcp_listener();
        let socket: async_std::net::TcpListener = socket.into();
        socket.bind("0.0.0.0").await?;

yoshuawuyts avatar Jan 14 '20 17:01 yoshuawuyts

@yoshuawuyts But what if i need TcpStream? async-std has only static connect function. Tokio has tokio::net::TcpStream::from_std() for this purpose.

        socket.set_reuse_address(true)?;
        socket.set_linger(Some(Duration::from_secs(0)))?;
        socket.bind(&"0.0.0.0:0".parse::<SocketAddr>()?.into())?;
        let socket = socket.into_tcp_stream();
        let stream: async_std::net::TcpStream = socket.into();
        // ??

Deniskore avatar Jan 14 '20 17:01 Deniskore

@Deniskore we provide From conversions for all std types. This includes TcpStream, so the example you wrote would indeed be the intended way to go about it.

yoshuawuyts avatar Jan 15 '20 07:01 yoshuawuyts

Tangential question: what happens if I transform a TcpSocket into a TcpStream or TcpListener without having called connect or accept?

piegamesde avatar Sep 13 '21 23:09 piegamesde