github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/pkg/socket/sockopts_unix.go (about)

     1  // Copyright (c) 2019 Andy Pan
     2  // Copyright (c) 2017 Joshua J Baker
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package socket
    17  
    18  import (
    19  	"os"
    20  
    21  	"github.com/pawelgaczynski/gain/pkg/errors"
    22  	"golang.org/x/sys/unix"
    23  )
    24  
    25  // SetKeepAlivePeriod sets whether the operating system should send
    26  // keep-alive messages on the connection and sets period between TCP keep-alive probes.
    27  func SetKeepAlivePeriod(fd, secs int) error {
    28  	if secs <= 0 {
    29  		return errors.ErrInvalidTimeDuration
    30  	}
    31  
    32  	if err := os.NewSyscallError("setsockopt", unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1)); err != nil {
    33  		return err
    34  	}
    35  
    36  	if err := os.NewSyscallError(
    37  		"setsockopt", unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_KEEPINTVL, secs),
    38  	); err != nil {
    39  		return err
    40  	}
    41  
    42  	return os.NewSyscallError("setsockopt", unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_KEEPIDLE, secs))
    43  }