control_unix.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. // +build !solaris,!windows
  7. package dialer
  8. import (
  9. "syscall"
  10. "golang.org/x/sys/unix"
  11. )
  12. var SupportsReusePort = false
  13. func init() {
  14. fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, unix.IPPROTO_IP)
  15. if err != nil {
  16. l.Debugln("Failed to create a socket", err)
  17. return
  18. }
  19. defer func() { _ = unix.Close(fd) }()
  20. err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  21. switch {
  22. case err == unix.ENOPROTOOPT || err == unix.EINVAL:
  23. l.Debugln("SO_REUSEPORT not supported")
  24. case err != nil:
  25. l.Debugln("Unknown error when determining SO_REUSEPORT support", err)
  26. default:
  27. l.Debugln("SO_REUSEPORT supported")
  28. SupportsReusePort = true
  29. }
  30. }
  31. func ReusePortControl(_, _ string, c syscall.RawConn) error {
  32. if !SupportsReusePort {
  33. return nil
  34. }
  35. var opErr error
  36. err := c.Control(func(fd uintptr) {
  37. opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  38. })
  39. if err != nil {
  40. return err
  41. }
  42. return opErr
  43. }