当前位置: 首页 > article >正文

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 StateCauseWho is responsible?Fix/Optimization
CLOSE_WAITServer didn’t close() the socket after client closed it.Server-side issue (socket left open).Ensure close(client_fd); is always called.
TIME_WAITServer 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.
    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.
    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:
    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.

http://www.kler.cn/a/599696.html

相关文章:

  • WebSocket 传输大量数据好不好?稳定不稳定
  • 使用 Docker 部署 mysql 应用
  • C stm32f10x LED亮
  • go命令使用
  • 【微服务】SpringCloudGateway网关
  • Android App安装列表获取
  • k8s基础知识总结node+pod(上)
  • 跨域,前端
  • 埋点数据采集方案
  • 机器学习结合伏羲模型高精度多尺度气象分析与降尺度实现
  • C++ 性能优化隐藏危机:忽视数据结构与内存细节,效率大打折扣
  • 常见中间件漏洞:Apache篇
  • 使用 ByteDance 的 UI-TARS Desktop 探索 AI 驱动的 GUI 自动化新前沿
  • 计算机网络的分类——按照按拓扑结构分类
  • OpenHarmony子系统整机启动流程
  • Spring漏洞再现
  • Java设计模式之解释器模式
  • 堆外内存 OOM:现象分析与优化方案
  • 3.24-3 接口测试断言
  • 【RabbitMQ高级特性】消息确认机制、持久化、发送方确认、TTL和死信队列