linux socket中tcp的time_wait的快速回收和重用

来源:互联网 发布:浙江基层卫生网络直报 编辑:程序博客网 时间:2024/05/01 10:13

最近项目中发现用screen启动socket老出错,在调试脚本中看出是screen 启动后,但是并没有将socket拉起;起初一直在查是不是由于screen启动机制导致的,后来和同事沟通发现是由于服务器端socket有大量的客户端连接时,当服务器主动kill掉socket的tcp端口时,再次立即重启,socket端口并不会成功启动,原因是服务器端口的连接处于time_wait状态。

解决方法:

我们可以通过调整内核参数来调整:

vi /etc/sysctl.conf

编辑文件,加入以下内容:
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
 

然后执行/sbin/sysctl -p让参数生效。

net.ipv4.tcp_syncookies = 1表示开启SYN Cookies。当出现SYN等待队列溢出时,启用cookies来处理,可防范少量SYN攻击,默认为0,表示关闭;

net.ipv4.tcp_tw_reuse = 1表示开启重用。允许将TIME-WAIT sockets重新用于新的TCP连接,默认为0,表示关闭;

net.ipv4.tcp_tw_recycle = 1表示开启TCP连接中TIME-WAIT sockets的快速回收,默认为0,表示关闭。

net.ipv4.tcp_fin_timeout修改系統默认的TIMEOUT时间

修改之后,再用命令查看TIME_WAIT连接数netstat -ant |grep “TIME_WAIT” |wc –l

在没有nat情况下还需要设置net.ipv4.tcp_timestamps = 1才能生效。

关于内核参数的详细介绍,可以参考官方文档。我们这里简要说明一下tcp_tw_recycle参数。它用来快速回收TIME_WAIT连接,不过如果在NAT环境下会引发问题。
RFC1323中有如下一段描述:
An additional mechanism could be added to the TCP, a per-host cache of the last timestamp received from any connection. This value could then be used in the PAWS mechanism to reject old duplicate segments from earlier incarnations of the connection, if the timestamp clock can be guaranteed to have ticked at least once since the old connection was open. This would require that the TIME-WAIT delay plus the RTT together must be at least one tick of the sender’s timestamp clock. Such an extension is not part of the proposal of this RFC.
大概意思是说TCP有一种行为,可以缓存每个连接最新的时间戳,后续请求中如果时间戳小于缓存的时间戳,即视为无效,相应的数据包会被丢弃。
Linux是否启用这种行为取决于tcp_timestamps和tcp_tw_recycle,因为tcp_timestamps缺省就是开启的,所以当tcp_tw_recycle被开启后,实际上这种行为就被激活了。在nat环境中会出现时间戳错乱的情况,后面的数据包就被丢弃了,具体的 表现通常是是客户端明明发送的SYN,但服务端就是不响应ACK。


0 0
原创粉丝点击