macOS 设置 TCP 握手连接超时,提升浏览器在糟糕网络下的访问体验

多年的疑惑今天居然被偶然解开了。

由于墙内糟糕的网络环境,而且ISP甚至wifi内还有墙中墙,所以很多域名是打不开的。

每次看浏览器在傻乎乎的转菊花,就觉得浪费时间。

  sudo sysctl  net.inet.tcp.keepinit=3000

这一条指令可以直接设置 macOS 的 TCP Keepalive 心跳包初始化时间设置为3000毫秒。

net.inet.tcp.keepinit默认值是 75000 ,单位是毫秒。注意 Linux 下没这设置,而且单位是 秒

这句话学究式的解释可以通过 man 4 tcp 得到,摘录几条:

TCP_CONNECTIONTIMEOUT The TCP_CONNECTIONTIMEOUT option allows to specify the timeout, in seconds, for new, non established TCP connections. This option can be useful for both active and passive TCP connections. The default value is specified by the MIB variable net.inet.tcp.keepinit.
tcp.keepinit Timeout, in milliseconds, for new, non-established TCP connections.

换句话说,就是 TCP 第一个 syn 包最多给3秒等待。超过3秒就拉倒,直接报 ERR_CONNECTION_TIMED_OUT 完事。

我觉得,如果一个域名和TCP端口3秒钟内无法完成握手,就别执着了。你再干等75秒也不可能连上。这个值只会影响初始连接的超时,一旦连上了怎么idle都不影响,所以不会影响游戏的tcp或者websocket的长连接。也不影响udp。

2021-07-06 补充:

重启保持有效:

  echo net.inet.tcp.keepinit=3000 | sudo tee -a /etc/sysctl.conf

2021-09-21 补充:

新版macOS 把 /etc/sysctl.conf 这文件给换位置了。应该是

  "/Users/Shared/Relocated Items/Configuration/private/etc/sysctl.conf"

Comments