How to set socket option SO_REUSEPORT?


#1

I’ve read the documentation for std::net and mio, and I’ve found some methods like set_nodelay and set_keepalive, but I haven’t found a way to set other socket options like SO_REUSEPORT and SO_REUSEADDR on a given socket. How can I do this?


#2

You can’t do this with TcpListener because it will call bind before you have the option to call setsockopt. I’m assuming you don’t mean to be portable? Then you can do it manually using libc and then convert the resulting fd into a TcpListener:

extern crate libc;
use std::os::unix::io::FromRawFd;

fn open_socket_reuse_addr(...) -> TcpListener {
    unsafe {
        let fd=libc::socket(...);
        // check for error
        libc::setsockopt(fd,...);
        // check for error
        libc::bind(fd,...);
        // check for error
        TcpListener::from_raw_fd(fd)
    }
}

#3

The net2 crate has a TcpBuilder that should let you set up the socket in this way: https://crates.io/crates/net2