libp2p / go-reuseport

reuse tcp/udp ports in golang
ISC License
765 stars 108 forks source link

should I set SO_REUSEADDR in go app #100

Closed tarmylan closed 1 year ago

tarmylan commented 1 year ago

In Go, the net.Listen function automatically sets the SO_REUSEADDR option by default when creating a listening socket. This ensures that the same address can be used by multiple sockets simultaneously, which is often required in server applications.

the source from go

func (fd *netFD) listenStream(laddr sockaddr, backlog int, ctrlFn func(string, string, syscall.RawConn) error) error {
    var err error
    if err = setDefaultListenerSockopts(fd.pfd.Sysfd); err != nil {
        return err
    }
    var lsa syscall.Sockaddr
    if lsa, err = laddr.sockaddr(fd.family); err != nil {
        return err
    }
    if ctrlFn != nil {
        c, err := newRawConn(fd)
        if err != nil {
            return err
        }
        if err := ctrlFn(fd.ctrlNetwork(), laddr.String(), c); err != nil {
            return err
        }
    }
    if err = syscall.Bind(fd.pfd.Sysfd, lsa); err != nil {
        return os.NewSyscallError("bind", err)
    }
    if err = listenFunc(fd.pfd.Sysfd, backlog); err != nil {
        return os.NewSyscallError("listen", err)
    }
    if err = fd.init(); err != nil {
        return err
    }
    lsa, _ = syscall.Getsockname(fd.pfd.Sysfd)
    fd.setAddr(fd.addrFunc()(lsa), nil)
    return nil
}

// unix 
func setDefaultListenerSockopts(s int) error {
    // Allow reuse of recently-used addresses.
    return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
}

func setDefaultMulticastSockopts(s int) error {
    // Allow multicast UDP and raw IP datagram sockets to listen
    // concurrently across multiple listeners.
    return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
}
Stebalien commented 1 year ago

I don't understand the question.

MarcoPolo commented 1 year ago

Unclear what the issue is, sorry. We already set reuse_port. Closing for now, feel free to comment again with some more info.