端口状态“LISTENING”、“TIME_WAIT”、“CLOSE_WAIT”和“ESTABLISHED”之间有什么区别?

Rou*_*ter 50 netstat

netstat用来检查我的端口状态。

我想知道什么是端口状态之间的区别LISTENINGTIME_WAITCLOSE_WAITFIN_WAIT1ESTABLISHED

mur*_*uru 65

联机帮助页netstat每个状态进行了简要说明:

   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.
Run Code Online (Sandbox Code Playgroud)

您可以使用状态转换图(此处此处此处的示例)来更好地了解状态。


考虑两个尝试套接字连接的程序(调用它们ab)。两者都设置套接字并转换到LISTEN状态。然后一个程序(例如a)尝试连接到另一个程序(b)。a发送请求进入SYN_SENT状态,b接收请求进入SYN_RECV状态。当b确认请求时,他们进入ESTABLISHED状态,并做他们的事情。现在可能会发生一些事情:

  1. a希望关闭连接,然后输入FIN_WAIT1b接收FIN请求,发送一个ACK(然后a进入FIN_WAIT2),进入CLOSE_WAIT,告诉a它正在关闭并且进入LAST_ACK。一旦a确认(并输入TIME_WAIT),b输入CLOSEa稍等片刻,看看是否还剩下任何东西,然后输入CLOSE
  2. ab已完成其业务并决定关闭连接(同时关闭)。当a在 中时FIN_WAIT,它不是接收ACKfrom b,而是接收 a FIN(也b希望关闭它),a进入CLOSING。但仍有一些消息发送(在ACK那个a应该得到原来的FIN),并且,一旦这ACK到达,a进入TIME_WAIT照常进行。