| 1 |
package reuseport |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"net" |
| 6 |
"syscall" |
| 7 |
|
| 8 |
"golang.org/x/sys/unix" |
| 9 |
) |
| 10 |
|
| 11 |
var listenConfig = net.ListenConfig{ |
| 12 |
Control: func(network, address string, c syscall.RawConn) (err error) { |
| 13 |
return c.Control(func(fd uintptr) { |
| 14 |
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) |
| 15 |
if err == nil { |
| 16 |
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) |
| 17 |
} |
| 18 |
}) |
| 19 |
}, |
| 20 |
} |
| 21 |
|
| 22 |
// Listen returns a TCP listener with the SO_REUSEADDR and SO_REUSEPORT options set. |
| 23 |
func Listen(network, addr string) (net.Listener, error) { |
| 24 |
return listenConfig.Listen(context.Background(), network, addr) |
| 25 |
} |