TCP netstat TIME_WAIT & CLOSE_WAIT

TIME_WAIT is different from CLOSE_WAIT, and it's not necessarily a client-side fault. It happens due to how TCP handles connection termination.

Key Differences

TCP State Cause Who is responsible? Fix/Optimization
CLOSE_WAIT Server didn't close() the socket after client closed it. Server-side issue (socket left open). Ensure close(client_fd); is always called.
TIME_WAIT Server closed the socket first, waiting to ensure the client received the FIN. Normal behavior (not necessarily a problem). Use SO_LINGER or SO_REUSEADDR to mitigate excessive TIME_WAIT.

Why Does TIME_WAIT Happen?

  • When your server calls close(client_fd); , it sends a FIN to the client.
  • If the client follows the normal TCP closure process , it replies with ACK and sends its own FIN, which your server then ACKs.
  • Your server enters TIME_WAIT for 2×MSL (Maximum Segment Lifetime, usually 60s total) to ensure any delayed packets are handled before fully releasing the connection.

Is TIME_WAIT the Client's Fault?

  • If the client closes the connection first , the server goes to CLOSE_WAIT (which we fixed).
  • If the server closes first , TIME_WAIT is expected.
  • Too many TIME_WAIT sockets? It usually means many short-lived connections are being closed quickly.

How to Reduce TIME_WAIT Issues?

  1. Enable SO_REUSEADDR

    • Allows immediate reuse of the same port, even in TIME_WAIT state.
    c 复制代码
    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  2. Use SO_LINGER to Force Immediate Closure

    • Not recommended unless necessary, as it can cause packet loss.
    c 复制代码
    struct linger sl;
    sl.l_onoff = 1;  // Enable linger
    sl.l_linger = 2; // Close socket after 2 seconds
    setsockopt(client_fd, SOL_SOCKET, SO_LINGER, &sl, sizeof(sl));
  3. Keep Connections Open Longer

    • If possible, reuse connections instead of opening/closing frequently.
  4. Tune TCP Stack (sysctl)

    • Reduce TIME_WAIT timeout if necessary:
    sh 复制代码
    sudo sysctl -p | grep net.ipv4.tcp_fin_timeout  # net.ipv4.tcp_fin_timeout = 2
    sysctl -w net.ipv4.tcp_fin_timeout=30

Conclusion

  • CLOSE_WAIT is a server-side issue (fixed by properly closing sockets).
  • TIME_WAIT is expected behavior when the server closes first.
  • Too many TIME_WAIT sockets? Use SO_REUSEADDR , linger options , or connection pooling if appropriate.
相关推荐
马拉萨的春天4 小时前
RTC、UDP、TCP和HTTP以及直播等区别
tcp/ip·udp·实时音视频
asdfg12589636 小时前
如何判断一个地址是否可以用作主机 IP 地址?
服务器·网络·tcp/ip
爱吃甜品的糯米团子7 小时前
Linux 学习笔记之进程管理、网络基础与常用软件安装
linux·网络·学习
ytttr8738 小时前
C语言实现Modbus TCP/IP协议客户端-服务器
服务器·c语言·tcp/ip
迷枫7128 小时前
19.1 TCP 和 UDP 有什么区别?
网络·tcp/ip·udp
取酒鱼食--【余九】9 小时前
深度学习经典网络解析:ResNet
网络·人工智能·深度学习·神经网络·resnet·卷积神经网络·残差神经网络
风清再凯9 小时前
05-k8s网络
网络·容器·kubernetes
LJ-SEU9 小时前
win-ubuntu网络转发
linux·网络·ubuntu
关关长语10 小时前
(一) Dotnet使用MCP的Csharp SDK
网络·.net·mcp
迎風吹頭髮11 小时前
Linux服务器编程实践26-TCP连接超时重连机制:超时时间计算与重连策略
服务器·网络·php