control_unix.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:build !solaris && !windows
  7. // +build !solaris,!windows
  8. package dialer
  9. import (
  10. "syscall"
  11. "golang.org/x/sys/unix"
  12. )
  13. var SupportsReusePort = false
  14. func init() {
  15. fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, unix.IPPROTO_IP)
  16. if err != nil {
  17. l.Debugln("Failed to create a socket", err)
  18. return
  19. }
  20. defer func() { _ = unix.Close(fd) }()
  21. err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  22. switch {
  23. case err == unix.ENOPROTOOPT || err == unix.EINVAL:
  24. l.Debugln("SO_REUSEPORT not supported")
  25. case err != nil:
  26. l.Debugln("Unknown error when determining SO_REUSEPORT support", err)
  27. default:
  28. l.Debugln("SO_REUSEPORT supported")
  29. SupportsReusePort = true
  30. }
  31. }
  32. func ReusePortControl(_, _ string, c syscall.RawConn) error {
  33. if !SupportsReusePort {
  34. return nil
  35. }
  36. var opErr error
  37. err := c.Control(func(fd uintptr) {
  38. opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  39. })
  40. if err != nil {
  41. return err
  42. }
  43. return opErr
  44. }