Allow UdpSocket to set socket options before bind

Hi,

Currently there is no way to set socket options before binding for UdpSocket, AFAIK. Normally we turn to crates like socket2 to do this. Can we add this functionality into stdlib itself?

Not sure if this was discussed before, but I wanted to propose adding a new bind function that takes in a parameter for setting socket options. For example:

pub fn bind_with_presets(addr: A, presets: Vec<SocketPreset>) -> Result<UdpSocket>

(A: ToSocketAddrs same as today)

Where SocketSet is an enum, something like:

#[non_exhaustive]
pub enum SocketPreset {
    REUSE_ADDR(bool),
    REUSE_PORT(bool),  // Platform dependent, only available on Unix
}

The new function will try to set socket options in presets before the normal binding, return error if failed.

What do you think? (I tried to propose more involved solutions before, but didn't get accepted. This is a much smaller change. Maybe it's a naive idea, but my goal is the same: use UdpSocket in stdlib as much as possible).

Not speaking for the rest of the libs-api team here, but I think something closer to a builder makes sense here: rather than a bunch of specialized functions to do things between socket and bind, I think it makes sense to have a builder for "create unbound socket, set various options, bind to consume the builder and get a bound socket".

1 Like

Just to note, any of the directly os-dependent functionality would generally be exposed via extension traits under std::os::{os}::net, e.g. UnixDatagram.

The existing precedent in std would be to use a simple fn(self) -> Self builder/factory.

That's true. But if there are both portable and non-portable options, the portable ones can live directly on the builder, and the non-portable ones can live in a sealed extension trait implemented for the builder.

1 Like

prior discussion: add UnboundUdpSocket to std::net · Issue #66 · rust-lang/libs-team · GitHub

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.