What's the difference between port status "LISTENING", "TIME_WAIT", " CLOSE_WAIT" and "ESTABLISHED"?
I use netstat
to check my port status.
I was wondering what's the difference between port status LISTENING
, TIME_WAIT
, CLOSE_WAIT
, FIN_WAIT1
and ESTABLISHED
?
The manpage of netstat
has a brief description of each state:
ESTABLISHED
The socket has an established connection.
SYN_SENT
The socket is actively attempting to establish a connection.
SYN_RECV
A connection request has been received from the network.
FIN_WAIT1
The socket is closed, and the connection is shutting down.
FIN_WAIT2
Connection is closed, and the socket is waiting for a shutdown
from the remote end.
TIME_WAIT
The socket is waiting after close to handle packets still in the
network.
CLOSE The socket is not being used.
CLOSE_WAIT
The remote end has shut down, waiting for the socket to close.
LAST_ACK
The remote end has shut down, and the socket is closed. Waiting
for acknowledgement.
LISTEN The socket is listening for incoming connections. Such sockets
are not included in the output unless you specify the
--listening (-l) or --all (-a) option.
CLOSING
Both sockets are shut down but we still don't have all our data
sent.
UNKNOWN
The state of the socket is unknown.
You can use the state transition diagrams (examples here, here and here) to make better sense of the states.
Consider two programs attempting a socket connection (call them a
and b
). Both set up sockets and transition to the LISTEN
state. Then one program (say a
) tries to connect to the other (b
). a
sends a request and enters the SYN_SENT
state, and b
receives the request and enters the SYN_RECV
state. When b
acknowledges the request, they enter the ESTABLISHED
state, and do their business. Now a couple of things can happen:
-
a
wishes to close the connection, and entersFIN_WAIT1
.b
receives theFIN
request, sends anACK
(thena
entersFIN_WAIT2
), entersCLOSE_WAIT
, tellsa
it is closing down and the entersLAST_ACK
. Oncea
acknowledges this (and entersTIME_WAIT
),b
entersCLOSE
.a
waits a bit to see if anythings is left, then entersCLOSE
. -
a
andb
have finished their business and decide to close the connection (simultaneous closing). Whena
is inFIN_WAIT
, and instead of receiving anACK
fromb
, it receives aFIN
(asb
wishes to close it as well),a
entersCLOSING
. But there are still some messages to send (theACK
thata
is supposed to get for its originalFIN
), and once thisACK
arrives,a
entersTIME_WAIT
as usual.