A Word on TIME_WAIT and CLOSE_WAIT
I’m surprised by the fact that so many network programmers don’t know TIME_WAIT and CLOSE_WAIT well, particularly those who use Java, C#, Python and etc.
It is true, however, TIME_WAIT and CLOSE_WAIT are the most confusing two among TCP’s 11 states (CLOSED, LISTEN, SYN_SENT, SYN_RECV, ESTABLISHED, CLOSE_WAIT, LAST_ACK, FIN_WAIT1, FIN_WAIT2, CLOSING, and TIME_WAIT), which are displayed by netstat(1).
Before going into detail, let me explain the terms first:
Active Open: An end sends a SYN segment to the other end by calling connect(2). This end is usually called a client.
Passive Open: An end issues a passive open by calling socket(2), bind(2), and listen(2) so that it can accept(2) the clients’ connections. This end is usually called a server.
Active Close: An end performs active close when it calls close(2) first. It results a FIN segment being sent.
Passive Close: The other end receives the FIN segment performs the passive close.
MSL: Maximum Segment Lifetime, the maximum time a segment can live in the network before being discarded.
Now take a look at the TCP state transition diagram.
In the diagrams above, I denote the active open/close transitions with a green line and the passive open/close transitions with a blue line (Normal transitions are in bold). The end that performs the active close goes through the TIME_WAIT state; while the end performs the passive close enters the CLOSE_WAIT state. Note that either end (the server or the client) can perform the active close!
What’s the TIME_WAIT state for?
1) When the final ACK being sent by the end that performed the active close was lost, the other end would resend a FIN. TCP maintains the information of the connection, hence it would resend the lost ACK rather than respond with an RST (interpreted as error).
2) To allow wandering duplicates to expire in the network, so that the duplicate segments would not corrupt later connections.
The value of TIME_WAIT delay is 2MSL, which is TCP implementation dependent and is generally about 1-4 minutes.
CLOSE_WAIT happens when an end has received a FIN segment from the other end, to wait for the program to close the socket. Long duration of CLOSE_WAIT suggests that there might be a bug in your program. In fact, a TCP connection can stay in the CLOSE_WAIT state forever unless it is explicitly closed. It is the application’s responsibility to close its socket after use, to release the resource of the connection.
Conclusion:
In most cases, there is no need to worry about TIME_WAIT. It is a safety feature of TCP. But you really should take care of CLOSE_WAIT. Also note, if a connection is in CLOSE_WAIT, it would never end up in the TIME_WAIT state, and vice versa. BTW, if you haven’t read Richard Stevens’ Unix Network Programming, go out and buy one. It is a must-have for all network programmers, even if you do Windows programming.
Download the dot files and msc file here:
http://www.zhuzhaoyuan.com/download/tcp/tcp-state1.dot
http://www.zhuzhaoyuan.com/download/tcp/tcp-state2.dot
http://www.zhuzhaoyuan.com/download/tcp/tcp_close.msc



mryufeng said,
March 9, 2009 @ 12:25 pm
excellent!
Tank said,
March 9, 2009 @ 1:15 pm
什么事情要讲场景,那些用Java, C#, Python的,绝大多数是搞上层应用的,用WCF(ok,管它xxF,反正我[们]要高层的封装抽象)的netTcpBinding就是了,哪管这些血淋淋的细节。如果WCF是一座大厦的1-10层,上面还有90层。
这不是有用没用的问题,而是性价比的问题,我[们]是engineer,嗯哼?
举个挑衅的例子,是不是每个程序要都要精通数字电路,狂玩与非门呢?
定位好自己的方向,这很重要。
Arbow said,
March 11, 2009 @ 10:39 am
多了解下还是好的,不过我感觉现在这些状态变迁图很难带来一个直观的认识,起码对我来说要死记这样图会更困难,或许该使用一些别的方式去方便记忆,比如MindMap
yufeng said,
March 11, 2009 @ 5:29 pm
to tank: 正常情况下 不需要精通的 但是如果你的程序出了问题 高手看状态图就知道你的程序socket错在哪里 就靠这张图 你能说没有吗?
Tank said,
March 12, 2009 @ 12:32 am
to yufeng:场景,场景。老朱如果把“Java, C#, Python”换成“C,C++”,我双手双脚赞成,他们本来就是做基础设施(lib,framework)和/或特殊应用的,肯定要精通tcp/socket。Java, C#这些程序员,也可以用诸如System.Net.Sockets来做原始的network programming,但,绝大多数是做诸如“做个集成飞机订票、旅馆、出租车服务的旅行服务”这样的network应用(ok,我承认我一开始就有点无理取闹,不过想想,老朱是多么心胸宽广的人啊:)。
the point is:我很纳闷现今还有多少场合需要raw socket programming,能否举些非用不可的例子?(网游不算哈,企业应用吧)
Joshua said,
March 12, 2009 @ 4:47 pm
Hey guys,
Relax, please. I blogged this because I hoped it would be helpful to somebody. It’s just for fun. You know, I did NOT expect it to be known by everybody. Well, if you consider it as nothing no more than meaningless crap, just forget it.
Tank said,
March 12, 2009 @ 7:58 pm
Yes, I’ve deleted some of your insane words.
Joshua.
Chris said,
March 25, 2009 @ 8:58 am
Hey joshua, i just read your post, its really good! Ignore the rude comments, you’ve been very helpful to me.
Joshua said,
March 26, 2009 @ 6:43 pm
Hi Chris, thank you very much for your sweet encouragement
TIME_WAIT vs CLOSE_WAIT « Praveen's Blog said,
August 1, 2009 @ 5:52 pm
[...] TIME_WAIT vs CLOSE_WAIT By praveenmyls Cool link CLOSE_WAIT vs TIMEWAIT [...]
Arrix said,
October 25, 2009 @ 11:41 am
Nice graphs and clear explanation! The meaning of CLOSE_WAIT and TIME_WAIT and the difference between them is also frequently asked in job interviews.
lzy said,
December 10, 2009 @ 7:14 pm
请教个问题,我在客户端程序里为socket fd设置了SO_LINGER选项,启用了linger。下面是客户端开始部分代码:
int sockfd = 0;
struct sockaddr_in addr;
struct linger lingopt;
/* some code here */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
err_sys(”create socket error”);
lingopt.l_onoff = 1;
lingopt.l_linger = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &lingopt, sizeof(lingopt)) != 0)
err_ret(”set linger option error”);
/* connect server */
if (connect(sockfd, (struct sockaddr*) &addr, sizeof(addr)) == -1)
err_sys(”connect error”);
/* other code here */
可见上面我打开了linger,并确认option被成功应用。这个客户端程序会在SIGQUIT后退出(ctrl+d)。程序退出后发现,尽管我已经成功的配置了linger选项l_onoff=1&l_linger=0,可是为什么当客户端程序退出后,通过netstat仍然可见TIME_WAIT状态的客户端socket?而不是客户端直接发RST并释放socket?还是os有配置的方法?我是Linux 2.6.31-15-generic #50-Ubuntu。
很简单的问题,之前一直想当然,今天无意中看到现象,还请赐教,多谢!
另外我设置linger不是为了避免主动关闭端的TIME_WAIT状态,它的2个作用是很必要的。之所以今天配置了SO_LINGER选项是为了验证特定问题,对于l_onoff=1&l_linger=0设置下FIN发起端还出现TIME_WAIT现象与之前的理解违背,(当然与unp所说的情况也不一致)。
Joshua said,
December 11, 2009 @ 6:46 pm
@lzy
我没有重现你说的问题。BTW,可加我gtalk详细讨论一下。
fy said,
January 2, 2010 @ 10:02 pm
请教下这2个 .dot 干嘛用呢?
我在lighttpd的源码里面也发现类似的文件?
fastcgi-state.dot state.dot
???
fy said,
January 2, 2010 @ 10:20 pm
graphviz, dotty - I found:)
sealinger said,
February 14, 2010 @ 4:59 pm
学习了,thanks
anonymous said,
May 4, 2010 @ 3:29 pm
a SYN segment ==> an SYN segment ???
moncler said,
November 16, 2010 @ 7:37 pm
可是为什么当客户端程序退出后,通过netstat仍然可见TIME_WAIT状态的客户端socket?而不是客户端直接发RST并释放socket?还是os有配置的方法?我是Linux 2.6.31-15-generic #50-Ubuntu。
DenisSilin19 said,
December 6, 2010 @ 11:11 am
недорогая реклама в прессе, СМИ, на тв Киеве
escort bayan said,
August 17, 2011 @ 5:33 am
Hi! I simply wanted to say your blog
Pete Windle said,
October 12, 2011 @ 9:24 pm
Thanks a lot for this, love the diagrams.
For those who believe in the power of high-level libraries, it’s easy to trigger these issues from those too:-)
personal loans said,
November 6, 2011 @ 8:43 am
According to my own analysis, billions of people in the world receive the credit loans at good creditors. Thus, there is great possibilities to find a bank loan in any country.
Dr Dre Beats Turbine pro said,
November 9, 2011 @ 9:43 pm
Artists and producers spend countless hours fine-tuning and mixing music to get it exactly how they want their fans to hear it. But the vast majority of headphones cant accurately reproduce the intricacies produced in the studio. Studios, simply put, can. With precision-engineered, advanced speaker design, powered amplification, and powered noise cancellation, you hear music the way todays top artists and producers want you to hear.
nike free shoes said,
November 10, 2011 @ 9:28 am
nike free shoes
Air Max Pas Cher said,
November 19, 2011 @ 4:22 pm
These are one of the few posts that I actually care to comment on. I find this blogger an inspiration and is definitely worth following. I’ve became a subscriber too, so please keep me updated.
yuda said,
December 27, 2011 @ 7:21 am
wow… awesome,
what a clear explanation, thanks
cell phone directory said,
January 31, 2012 @ 4:14 am
Thanks for the entertaining and informative post. I enjoy the way you express your thoughts. And this explains the reason for writing this particular comment and also why I continue to visit this website again and again.