sockopt_bsd.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build darwin || dragonfly || freebsd || netbsd || openbsd
  5. package net
  6. import (
  7. "os"
  8. "runtime"
  9. "syscall"
  10. )
  11. func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
  12. if runtime.GOOS == "dragonfly" && sotype != syscall.SOCK_RAW {
  13. // On DragonFly BSD, we adjust the ephemeral port
  14. // range because unlike other BSD systems its default
  15. // port range doesn't conform to IANA recommendation
  16. // as described in RFC 6056 and is pretty narrow.
  17. switch family {
  18. case syscall.AF_INET:
  19. syscall.SetsockoptInt(s, syscall.IPPROTO_IP, syscall.IP_PORTRANGE, syscall.IP_PORTRANGE_HIGH)
  20. case syscall.AF_INET6:
  21. syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_PORTRANGE, syscall.IPV6_PORTRANGE_HIGH)
  22. }
  23. }
  24. if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW && supportsIPv4map() {
  25. // Allow both IP versions even if the OS default
  26. // is otherwise. Note that some operating systems
  27. // never admit this option.
  28. syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
  29. }
  30. if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX {
  31. // Allow broadcast.
  32. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
  33. }
  34. return nil
  35. }
  36. func setDefaultListenerSockopts(s int) error {
  37. // Allow reuse of recently-used addresses.
  38. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
  39. }
  40. func setDefaultMulticastSockopts(s int) error {
  41. // Allow multicast UDP and raw IP datagram sockets to listen
  42. // concurrently across multiple listeners.
  43. if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
  44. return os.NewSyscallError("setsockopt", err)
  45. }
  46. // Allow reuse of recently-used ports.
  47. // This option is supported only in descendants of 4.4BSD,
  48. // to make an effective multicast application that requires
  49. // quick draw possible.
  50. if syscall.SO_REUSEPORT != 0 {
  51. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEPORT, 1))
  52. }
  53. return nil
  54. }