tcp_keepalive_unix.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //go:build unix
  2. /*
  3. * Copyright 2023 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package internal
  19. import (
  20. "net"
  21. "syscall"
  22. "time"
  23. "golang.org/x/sys/unix"
  24. )
  25. // NetDialerWithTCPKeepalive returns a net.Dialer that enables TCP keepalives on
  26. // the underlying connection with OS default values for keepalive parameters.
  27. //
  28. // TODO: Once https://github.com/golang/go/issues/62254 lands, and the
  29. // appropriate Go version becomes less than our least supported Go version, we
  30. // should look into using the new API to make things more straightforward.
  31. func NetDialerWithTCPKeepalive() *net.Dialer {
  32. return &net.Dialer{
  33. // Setting a negative value here prevents the Go stdlib from overriding
  34. // the values of TCP keepalive time and interval. It also prevents the
  35. // Go stdlib from enabling TCP keepalives by default.
  36. KeepAlive: time.Duration(-1),
  37. // This method is called after the underlying network socket is created,
  38. // but before dialing the socket (or calling its connect() method). The
  39. // combination of unconditionally enabling TCP keepalives here, and
  40. // disabling the overriding of TCP keepalive parameters by setting the
  41. // KeepAlive field to a negative value above, results in OS defaults for
  42. // the TCP keealive interval and time parameters.
  43. Control: func(_, _ string, c syscall.RawConn) error {
  44. return c.Control(func(fd uintptr) {
  45. unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1)
  46. })
  47. },
  48. }
  49. }