天天看点

tcp短连接TIME_WAIT问题解决方法大全(5)——tcp_max_tw_buckets

参考官方文档(http://www.kernel.org/doc/documentation/networking/ip-sysctl.txt),解释如下:

tcp_max_tw_buckets - integer

maximal number of timewait sockets held by system simultaneously.

if this number is exceeded time-wait socket is immediately destroyed

and warning is printed. 

官方文档没有说明默认值,通过几个系统的简单验证,初步确定默认值是180000。

通过源码查看发现,这个选项比较简单,其实现代码如下:

=====linux-2.6.37 net/ipv4/tcp_minisocks.c 269======

void tcp_time_wait(struct sock *sk, int state, int timeo)

{

struct inet_timewait_sock *tw = null;

const struct inet_connection_sock *icsk = inet_csk(sk);

const struct tcp_sock *tp = tcp_sk(sk);

int recycle_ok = 0;

if (tcp_death_row.sysctl_tw_recycle && tp->rx_opt.ts_recent_stamp)

recycle_ok = icsk->icsk_af_ops->remember_stamp(sk);

if (tcp_death_row.tw_count < tcp_death_row.sysctl_max_tw_buckets)

tw = inet_twsk_alloc(sk, state);

if (tw != null) {

        //分配成功,进行time_wait状态处理,此处略去很多代码

    else {

        //分配失败,不进行处理,只记录日志: tcp:

time wait bucket table overflow

/* sorry, if we're out of memory, just close this

* socket up.  we've got bigger problems than

* non-graceful socket closings.

*/

net_inc_stats_bh(sock_net(sk), linux_mib_tcptimewaitoverflow);

}

tcp_update_metrics(sk);

tcp_done(sk);

实测结果验证,配置为100,time_wait连接数就稳定在100,且不受组网和其它配置的影响。

官方手册中有一段警告:

    this limit exists only to prevent

simple dos attacks, you _must_ not lower the limit artificially,

but rather increase it (probably, after increasing installed memory),

if network conditions require more than default value.

基本意思是这个用于防止dos攻击,我们不应该人工减少,如果网络条件需要的话,反而应该增加。

但其实对于我们的局域网或者公司内网应用来说,这个风险并不大。

继续阅读