How to set socket option SO_REUSEPORT?


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?


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
        // check for error
        // check for error


The net2 crate has a TcpBuilder that should let you set up the socket in this way: