[PATCH] conn: set the SO_REUSEADDR and SO_REUSEPORT socket options

Hiram Chirino hiram at hiramchirino.com
Fri Apr 7 20:26:38 UTC 2023


Setting the SO_REUSEADDR and SO_REUSEPORT socket options allows other
applications to reuse the wg UDP port. This can be super handy to do
Things like sending stun requests to stun servers from the wg port.
This lets you discover the wg’s public IP:port mapping if you're behind a
NAT router.

Signed-off-by: Hiram Chirino <hiram at hiramchirino.com>
---
conn/controlfns_reuseport_unix.go | 32 ++++++++++++++++++++++++++++
conn/controlfns_reuseport_windows.go | 24 +++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 conn/controlfns_reuseport_unix.go
create mode 100644 conn/controlfns_reuseport_windows.go

diff --git a/conn/controlfns_reuseport_unix.go
b/conn/controlfns_reuseport_unix.go
new file mode 100644
index 0000000..44d617b
--- /dev/null
+++ b/conn/controlfns_reuseport_unix.go
@@ -0,0 +1,32 @@
+//go:build !plan9 && !windows && !wasm && !js
+
+/* SPDX-License-Identifier: MIT
+ *
+ * Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved.
+ */
+
+package conn
+
+import (
+ "golang.org/x/sys/unix"
+ "syscall"
+)
+
+func init() {
+
+ controlFns = append(controlFns,
+ func(network, address string, c syscall.RawConn) error {
+ return c.Control(func(fd uintptr) {
+ _ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
+ })
+ },
+ )
+ controlFns = append(controlFns,
+ func(network, address string, c syscall.RawConn) error {
+ return c.Control(func(fd uintptr) {
+ _ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
+ })
+ },
+ )
+
+}
diff --git a/conn/controlfns_reuseport_windows.go
b/conn/controlfns_reuseport_windows.go
new file mode 100644
index 0000000..2f8a7bf
--- /dev/null
+++ b/conn/controlfns_reuseport_windows.go
@@ -0,0 +1,24 @@
+//go:build windows
+
+/* SPDX-License-Identifier: MIT
+ *
+ * Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved.
+ */
+
+package conn
+
+import (
+ "syscall"
+
+ "golang.org/x/sys/windows"
+)
+
+func init() {
+ controlFns = append(controlFns,
+ func(network, address string, c syscall.RawConn) error {
+ return c.Control(func(fd uintptr) {
+ _ = windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET,
windows.SO_REUSEADDR, 1)
+ })
+ },
+ )
+}
-- 
2.37.1 (Apple Git-137.1)


More information about the WireGuard mailing list