TCP Closure

今天在看TCP的释放时遇到几个问题,查了一下《TCP/IP详解 卷一》和RFC793,也请教了一下Herbert Xu,基本上都解决了。在这里总结一下。

TCP的释放过程如下图所示(取自《TCP/IP详解 卷一》):

问题1:既然TCP的CLOSE是单工的,那么,一方在收到FIN的ACK之后可能会过很长一段时间才收到对方的FIN。那么如果这个时间里这方已经关闭该进程,谁又来ACK对方的FIN呢?

Herbert解释到:

For you particular scenario, the key is that the TCP socket is
maintained by the OS, not the process.

So even after your process has called close(2) and exited, the
OS will continue to respond in ways required by RFC793 until
such a time when the socket has been CLOSEed in the sense of the
protocol.
问题2:两方同时发送FIN又如何呢?

没想到这个问题连RFC里都有,里面这样解释:

A simultaneous CLOSE by users at both ends of a connection causes
FIN segments to be exchanged. When all segments preceding the FINs
have been processed and acknowledged, each TCP can ACK the FIN it
has received. Both will, upon receiving these ACKs, delete the
connection.
也就是像下图所示(也是取自TCP/IP详解):

问题3:关于MSL。

MSL是maximum segment lifetime的缩写。TCP状态机里有个TIME_WAIT状态,设置它是为了防止最后一个ACK丢失,这个时间一般就是2MSL。而且,在这个2MSL的时间中,这个socket是不能被重用的,除非我们setsockopt(…,SO_REUSEADDR,…)。