sockopt_bsd.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // +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 {
  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. // Allow broadcast.
  31. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
  32. }
  33. func setDefaultListenerSockopts(s int) error {
  34. // Allow reuse of recently-used addresses.
  35. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
  36. }
  37. func setDefaultMulticastSockopts(s int) error {
  38. // Allow multicast UDP and raw IP datagram sockets to listen
  39. // concurrently across multiple listeners.
  40. if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
  41. return os.NewSyscallError("setsockopt", err)
  42. }
  43. // Allow reuse of recently-used ports.
  44. // This option is supported only in descendants of 4.4BSD,
  45. // to make an effective multicast application that requires
  46. // quick draw possible.
  47. if syscall.SO_REUSEPORT != 0 {
  48. return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEPORT, 1))
  49. }
  50. return nil
  51. }