I wrote a simple tcp client and server
and ran them
I notice that when I use ctrl+c
to end the program
the tcp connection be be closed
but the tcp connection state is like TIME_WAIT
then if I run the tcp client and server again
the tcp connection can't be established again
a RST
packet is always sent by the tcp server
I have to wait for some time until the next tcp connection can be established
what is the reason for this and how to deal with this problem?
besides, I notice on one host, when a tcp connection is in state FIN_WAIT_2
even if it doesn't receive FIN
, the tcp connection will become closed some time later
,why?
thanks
The solution for this problem is to set the SO_REUSEADDR socket option. This tells the stack to allow a bind on addresses that happen to be in the TIME_WAIT state.
The reason for the TIME_WAIT state seems to be to allow some time for the straggler packets to arrive. If the stack cannot make sure that the connection was shutdown gracefully, there maybe packets in transit or the sender may even be sending more data actively. The stack wants to avoid mixing these packets with the traffic of a newly bound connection.
Here is a good answer on the use of SO_REUSEADDR for TCP and UDP.