大网数据广告活动
服务器运维问答

why linux reuse 'time_wait' port?

· 52CE 我爱测

As I know, tcp port in 'time_wait' stat cann't be used. However, in my experiment, server reuses the 'time_wait' port? Why? Firstly, in client machine, type command ehco 40000 40001 > /proc/sys/net/ipv4/ip_local_port_range . So, …

问题原文

原帖链接 · Pengcheng · CC BY-SA 3.0

As I know, tcp port in 'time_wait' stat cann't be used. However, in my experiment, server reuses the 'time_wait' port? Why?

Firstly, in client machine, type command ehco 40000 40001 > /proc/sys/net/ipv4/ip_local_port_range. So, the maximum number of TCP ports is 2.

server code

while (1) {
    int len = sizeof(struct sockaddr);
    fd = accept(sfd, &remote, &len);

    read(fd, buf, sizeof(buf));
    close(fd);
}

client code

    for (i = 0; i < 3; i++)
    {
        sleep(1);
        pid_t pid = fork();
        if (pid == 0)
        {
            handler();
            exit(0);
        }
    }

 void handler()
 {
      * ............. */

      res = connect(sfd, result->ai_addr, result->ai_addrlen);
      if (res == -1) {
        perror("error");
        exit(1);
      }

      printf("connect\n");
 }

show

[root@livecd ~]# ./client 
connect
[root@livecd ~]# connect
connect

It's up to 3 connections. I think, 2 connections at most. Why ? server has 2 timewait connections.

[root@livecd ~]# netstat -anp | grep TIME
tcp  192.168.88.131:2016   192.168.88.132:40000  TIME_WAIT                  
tcp  192.168.88.131:2016   192.168.88.132:40001  TIME_WAIT                              

Environment

Linux livecd.centos 2.6.32-642.el6.i686 #1 SMP Tue May 10 16:13:51 UTC 2016

server config

[root@livecd ~]# cat /proc/sys/net/ipv4/tcp_fin_timeout 
60
[root@livecd ~]# cat /proc/sys/net/ipv4/tcp_tw_recycle 
0
[root@livecd ~]# cat /proc/sys/net/ipv4/tcp_tw_reuse 
0

client config

[root@livecd ~]# cat /proc/sys/net/ipv4/ip_local_port_range 
40000   40001

Important I also try ubuntu server 14.04, but got the same result.

已采纳解答

原帖链接 · Mark Riddell · CC BY-SA 3.0

The Time Wait state is used prevent old packets from a previous connection from being accepted into a new connection. It effectively allows enough time for old packets to "die" in the network.

However, a socket in Timewait state can accept a new connection as long as the Initial Sequence Number on the SYN is higher than the last sequence number seen on the socket.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-07-27)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。