github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/control/tcp_keep_alive_linux.go (about)

     1  package control
     2  
     3  import (
     4  	"syscall"
     5  	"time"
     6  	_ "unsafe"
     7  
     8  	E "github.com/sagernet/sing/common/exceptions"
     9  	N "github.com/sagernet/sing/common/network"
    10  
    11  	"golang.org/x/sys/unix"
    12  )
    13  
    14  func SetKeepAlivePeriod(idle time.Duration, interval time.Duration) Func {
    15  	return func(network, address string, conn syscall.RawConn) error {
    16  		if N.NetworkName(network) != N.NetworkTCP {
    17  			return nil
    18  		}
    19  		return Raw(conn, func(fd uintptr) error {
    20  			return E.Errors(
    21  				unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPIDLE, int(roundDurationUp(idle, time.Second))),
    22  				unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPINTVL, int(roundDurationUp(interval, time.Second))),
    23  			)
    24  		})
    25  	}
    26  }
    27  
    28  func roundDurationUp(d time.Duration, to time.Duration) time.Duration {
    29  	return (d + to - 1) / to
    30  }