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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值