Is there a way to bind tokio::TcpStream to a specific interface?

I am trying to use a specific interface with TcpStream but apparently both std and tokio TcpStreams dont support binding to interface.
Is there a way to do this in tokio or with any tokio compatible async library?
PS. I am planing to use Socket2 and use set_nonblocking on the tcpstream and poll it and use delay_for in between. Is there any downsides of this approach?

You can convert a socket created with socket2 into a Tokio TcpStream and use it normally.

use tokio::net::TcpStream;

let tcp_stream = spawn_blocking(move || {
    let socket = /* create socket using socket2 */;
    TcpStream::from_std(socket.into_tcp_stream())
}).await?;

similar question

I don't recommend using delay_for, since by converting it to a Tokio TcpStream, it can integrate with the Tokio event-loop. You do not need to set the nonblocking flag.

wont blocking entire thread per request reduce my throughput?

Maybe, but it's probably not too bad considering it's only the connect-part. It's probably much better than the delay_for suggestion. The alternative is to go through PollEvented and do something similar to this. I am unsure how this exactly fits in with socket2.

Oh so reads wont be blocking. I missed that part i guess.
PS. I found another solution using net2::TcpBuilder which seems to fit my needs

I assume that solution also involves converting it to a Tokio TcpStream?

yes it does but i can create an unconnected tcpstream instance in net2 case which doesnt block at all

UPDATE:
tokio implemented this feature so starting with 0.3 I believe we can create a TcpSocket and bind it to an interface without needing socket2 or net2

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.