Inbounds & Outbounds: TCP KeepAlive better default value (#4931)

From https://github.com/XTLS/Xray-core/pull/4927
This commit is contained in:
风扇滑翔翼 2025-07-25 20:06:05 +08:00 committed by GitHub
parent 87d8b97d9a
commit eb433d9462
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 46 additions and 28 deletions

View file

@ -3,6 +3,7 @@ package internet
import (
"context"
"math/rand"
gonet "net"
"syscall"
"time"
@ -87,14 +88,34 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne
Dest: destAddr,
}, nil
}
goStdKeepAlive := time.Duration(0)
if sockopt != nil && (sockopt.TcpKeepAliveInterval != 0 || sockopt.TcpKeepAliveIdle != 0) {
goStdKeepAlive = time.Duration(-1)
// Chrome defaults
keepAliveConfig := gonet.KeepAliveConfig{
Enable: true,
Idle: 45 * time.Second,
Interval: 45 * time.Second,
Count: -1,
}
keepAlive := time.Duration(0)
if sockopt != nil {
if sockopt.TcpKeepAliveIdle*sockopt.TcpKeepAliveInterval < 0 {
return nil, errors.New("invalid TcpKeepAliveIdle or TcpKeepAliveInterval value: ", sockopt.TcpKeepAliveIdle, " ", sockopt.TcpKeepAliveInterval)
}
if sockopt.TcpKeepAliveIdle < 0 || sockopt.TcpKeepAliveInterval < 0 {
keepAlive = -1
keepAliveConfig.Enable = false
}
if sockopt.TcpKeepAliveIdle > 0 {
keepAliveConfig.Idle = time.Duration(sockopt.TcpKeepAliveIdle) * time.Second
}
if sockopt.TcpKeepAliveInterval > 0 {
keepAliveConfig.Interval = time.Duration(sockopt.TcpKeepAliveInterval) * time.Second
}
}
dialer := &net.Dialer{
Timeout: time.Second * 16,
LocalAddr: resolveSrcAddr(dest.Network, src),
KeepAlive: goStdKeepAlive,
Timeout: time.Second * 16,
LocalAddr: resolveSrcAddr(dest.Network, src),
KeepAlive: keepAlive,
KeepAliveConfig: keepAliveConfig,
}
if sockopt != nil || len(d.controllers) > 0 {