From 28dc0654fa5a6bd8237d92caa60d605ac932ef7b Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Tue, 25 Apr 2023 22:20:04 +1000 Subject: [PATCH] fix error handling when setting socket options (#102) Both sockopt and control errors can't exist at the same time, but control errors should occur first, and so are given precedence. Fixes #101 --- control_unix.go | 14 ++++++-------- control_windows.go | 6 +++++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/control_unix.go b/control_unix.go index 06a0572..4197d1f 100644 --- a/control_unix.go +++ b/control_unix.go @@ -8,18 +8,16 @@ import ( "golang.org/x/sys/unix" ) -func Control(network, address string, c syscall.RawConn) error { - var err error - c.Control(func(fd uintptr) { +func Control(network, address string, c syscall.RawConn) (err error) { + controlErr := c.Control(func(fd uintptr) { err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) if err != nil { return } - err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) - if err != nil { - return - } }) - return err + if controlErr != nil { + err = controlErr + } + return } diff --git a/control_windows.go b/control_windows.go index 840534c..c45e43f 100644 --- a/control_windows.go +++ b/control_windows.go @@ -7,7 +7,11 @@ import ( ) func Control(network, address string, c syscall.RawConn) (err error) { - return c.Control(func(fd uintptr) { + controlErr := c.Control(func(fd uintptr) { err = windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1) }) + if controlErr != nil { + err = controlErr + } + return }