I. Overview of TCP Connection Management
TCP is a connection-oriented, reliable transport-layer protocol based on byte streams. Before actually transmitting data, both communicating parties must first establish a connection; after communication ends, they must release the connection according to the protocol process.
TCP connection management mainly includes two processes:
- Connection establishment: Through the three-way handshake, the client and server confirm each other's communication capabilities and synchronize initial sequence numbers.
- Connection release: Through the four-way handshake, close the data transmission channels in both directions separately, ensuring that data already sent can be delivered normally.
TCP connections have the following characteristics:
- Connection-oriented: a connection must be established before transmitting data.
- Full-duplex: both sides can send and receive data simultaneously.
- Reliable transmission: mechanisms such as sequence numbers, acknowledgments, and timeout retransmission ensure reliable data delivery.
- Ordered transmission: the receiver reassembles data according to sequence numbers.
- Byte stream: TCP does not preserve application-layer message boundaries.
1. What identifies a TCP connection?
TCP uses a four-tuple to uniquely identify a connection:
| Field | Meaning | Example |
|---|---|---|
| Source IP | IP address of the party initiating communication | 192.168.1.10 |
| Source port | Port of the party initiating communication | 52000 |
| Destination IP | IP address of the party receiving communication | 192.168.1.20 |
| Destination port | Port of the party receiving communication | 8080 |
For example:
Client: 192.168.1.10:52000
Server: 192.168.1.20:8080
This TCP connection can be represented as:
192.168.1.10:52000 <-> 192.168.1.20:8080
The same server IP and port can establish connections with multiple clients at the same time, because different connections usually have different client IPs or source ports.
For example:
192.168.1.10:52000 -> 192.168.1.20:8080
192.168.1.11:52001 -> 192.168.1.20:8080
192.168.1.12:52002 -> 192.168.1.20:8080
This is also the basis for a TCP server being able to serve a large number of clients simultaneously.
II. TCP Three-Way Handshake
1. Why is connection establishment necessary?
Suppose the client needs to send an HTTP request to the server.
Before formally transmitting data, both parties need to resolve several issues:
- Can the client send data to the server?
- Can the server receive the client's data?
- Can the server send data to the client?
- Can the client receive the server's data?
- How do both parties determine the sequence numbers for subsequent data?
TCP solves these problems through the three-way handshake.
The three-way handshake is not merely the client and server greeting each other; it also handles responsibilities such as synchronizing initial sequence numbers, confirming both parties' send and receive capabilities, and preventing stale connection requests from interfering with the current connection.
2. Complete process of the three-way handshake
Suppose:
- The client's initial sequence number is
ISN_C = 1000 - The server's initial sequence number is
ISN_S = 5000
The three-way handshake process is as follows:
sequenceDiagram
participant C as Client
participant S as Server
C->>S: SYN=1, seq=1000
Note over C: SYN-SENT
Note over S: LISTEN
S->>C: SYN=1, ACK=1, seq=5000, ack=1001
Note over S: SYN-RECEIVED
C->>S: ACK=1, seq=1001, ack=5001
Note over C,S: ESTABLISHED
The following is a step-by-step analysis.
First handshake: Client sends SYN
The client actively initiates the connection and sends a SYN segment to the server.
Key fields:
SYN = 1
SEQ = 1000
Meaning:
SYN = 1: indicates that this is a connection establishment request.SEQ = 1000: the initial sequence number chosen by the client.
After the client sends the SYN, it enters:
SYN-SENT
At this point, the client waits for the server's response.
After receiving the SYN, the server knows that the client wants to establish a connection and also knows the initial sequence number chosen by the client.
However, the server has not yet confirmed whether the client can receive its response.
Second handshake: Server returns SYN + ACK
After the server receives the client's SYN, it sends a SYN + ACK segment to the client.
Key fields:
SYN = 1
ACK = 1
SEQ = 5000
ACK_NUM = 1001
Meaning:
SYN = 1: The server also needs to synchronize its own initial sequence number.ACK = 1: Acknowledges that the client's connection request has been received.SEQ = 5000: The server's own initial sequence number.ACK_NUM = 1001: The next sequence number it expects to receive from the client.
Why is the acknowledgment number 1001?
Because although the SYN flag does not carry application data, it consumes one sequence number.
Therefore:
ACK_NUM = ISN_C + 1
= 1000 + 1
= 1001
After the server sends SYN + ACK, it enters:
SYN-RECEIVED
At this point, the server has acknowledged the request sent by the client, but it still needs to wait for the client to acknowledge the server's own SYN.
Third Handshake: The Client Sends an ACK
After the client receives the server's SYN + ACK, it sends an ACK to the server.
Key fields:
SYN = 0
ACK = 1
SEQ = 1001
ACK_NUM = 5001
Meaning:
ACK = 1: Acknowledges that the server's SYN has been received.SEQ = 1001: The next sequence number the client will send.ACK_NUM = 5001: The next sequence number it expects to receive from the server.
The server's SYN also consumes one sequence number:
ACK_NUM = ISN_S + 1
= 5000 + 1
= 5001
After the client sends the ACK, it enters:
ESTABLISHED
After the server receives the ACK, it also enters:
ESTABLISHED
At this point, the TCP connection is established.
3. State Changes in the Three-Way Handshake
Establishing a TCP connection involves the following states:
| State | Meaning |
|---|---|
| CLOSED | No connection is currently established |
| LISTEN | The server is listening for connection requests |
| SYN-SENT | The client has sent SYN and is waiting for a response |
| SYN-RECEIVED | The server has received SYN and has replied with SYN + ACK |
| ESTABLISHED | The TCP connection is established |
State transitions:
flowchart TD
A["Client CLOSED"] --> B["Send SYN"]
B --> C["Client SYN-SENT"]
D["Server CLOSED"] --> E["Call listen"]
E --> F["Server LISTEN"]
C --> G["Server receives SYN"]
F --> G
G --> H["Send SYN + ACK"]
H --> I["Server SYN-RECEIVED"]
I --> J["Client receives SYN + ACK"]
J --> K["Send ACK"]
K --> L["Client ESTABLISHED"]
K --> M["Server receives ACK"]
M --> N["Server ESTABLISHED"]
style A fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style D fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style J fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style M fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style N fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
Note: In the actual TCP state machine, the condition for the server to enter ESTABLISHED is receiving a valid ACK from the third handshake, not merely sending an ACK.
4. Why does TCP need a three-way handshake?
A common question is:
Why can't we use only a two-step handshake?
A two-step handshake roughly looks like this:
sequenceDiagram
participant C as Client
participant S as Server
C->>S: SYN
S->>C: SYN + ACK
Note over C,S: If it ends here, the server cannot confirm whether the client received the response
After the server receives the client's SYN, it can confirm:
- The client can send data.
- The server can receive data.
After the server sends SYN + ACK, it still cannot confirm:
- Whether the client successfully received the server's SYN.
- Whether the client can receive the server's data.
The third handshake is the client's acknowledgment of the server's SYN.
The complete process is:
| Handshake | Client | Server |
|---|---|---|
| First | Sends SYN | Receives SYN |
| Second | Receives SYN + ACK | Sends SYN + ACK |
| Third | Sends ACK | Receives ACK |
After the third handshake completes, both sides can confirm that the other has received their connection-establishment packet.
In addition, the third handshake can also prevent erroneous connection establishment caused by historical connection requests.
5. Why can the three-way handshake avoid interference from historical SYN requests?
Suppose there is an old SYN packet in the network that arrives late.
The client previously initiated a connection, but due to network delay, the old SYN never reached the server.
Later, the client abandoned this connection and initiated a new connection.
If a two-step handshake were used, the server might directly consider the connection established after receiving the old SYN.
But in the three-way handshake:
- The server receives the old SYN.
- The server returns SYN + ACK.
- The client finds that this response does not belong to the currently valid connection, and usually does not send a valid third acknowledgment.
- The server cannot complete normal connection establishment.
Therefore, the third handshake provides a final confirmation mechanism.
It should be noted that the three-way handshake cannot guarantee that old packets will never exist in the network, but through sequence numbers and acknowledgment mechanisms, it can prevent a valid connection from being established based solely on a historical SYN.
6. Why does SYN consume a sequence number?
TCP uses sequence numbers to identify data positions in the byte stream.
Although SYN and FIN do not carry application-layer data, they each consume one sequence number.
For example:
The client sends:
SYN = 1
SEQ = 1000
Next sequence number:
1001
If the client then sends 100 bytes of data:
SEQ = 1001
Data length = 100
Then when the receiver acknowledges the next expected sequence number:
ACK = 1101
It can be summarized as:
Next sequence number = Current sequence number + Data length + SYN occupancy + FIN occupancy
Here, SYN and FIN each occupy at most one sequence number.
III. Abnormal Situations in the Three-Way Handshake
Under normal circumstances, the three-way handshake can complete smoothly. But in real networks, packets may be lost, delayed, duplicated, or rejected.
1. The First SYN Is Lost
The client sends SYN, but SYN is lost in the network.
The client does not receive a response from the server, so it waits for a timeout and then resends SYN.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: SYN
Note over S: SYN lost
Note over C: Waiting for timeout
C->>S: Retransmit SYN
S->>C: SYN + ACK
C->>S: ACK
Note over C,S: Connection established successfully
TCP will send the connection request again according to the retransmission mechanism.
The specific retransmission interval is determined by the operating system's TCP implementation and configuration; it should not be simplistically understood as all systems waiting a fixed number of seconds.
2. The Second SYN + ACK Is Lost
After receiving SYN, the server sends SYN + ACK, but the response is lost.
At this point:
- The client is still in
SYN-SENT. - The server is in
SYN-RECEIVED. - The client has not received the acknowledgment response.
- The server has also not received the third handshake ACK.
Both sides may trigger retransmission separately.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: SYN
S->>C: SYN + ACK
Note over C: SYN + ACK lost
Note over C: Waiting for timeout
C->>S: Retransmit SYN
S->>C: Retransmit SYN + ACK
C->>S: ACK
Note over C,S: Connection established successfully
3. The Third ACK Is Lost
The client received the server's SYN + ACK and sent the third ACK, but the ACK is lost.
At this point:
- The client has entered
ESTABLISHED. - The server is still in
SYN-RECEIVED.
If the client starts sending data, the data packet can usually also acknowledge the server's SYN, because data packets can also carry the ACK flag.
If there is no subsequent data, the server may retransmit SYN + ACK, and the client will acknowledge it again upon receipt.
Therefore, the loss of the third ACK does not mean the connection will necessarily fail.
4. Server returns RST
If no process is listening on the server port, it will usually return an RST packet after receiving a connection request.
The client may get:
Connection refused
For example:
Client connects to 192.168.1.20:8080
No process is listening on port 8080 on the server
Server returns RST
Client connection fails
This is different from a connection timeout:
Connection refused: usually means the connection request was explicitly rejected.Connection timed out: usually means no valid response was received within the specified time.
5. SYN Flood Attack
SYN Flood is a denial-of-service attack that exploits the TCP three-way handshake process.
The attacker sends a large number of SYN requests to the server but does not complete the third handshake.
After receiving a SYN, the server needs to maintain a half-open connection state:
SYN
|
v
SYN-RECEIVED
|
v
Waiting for ACK
If a large number of connections remain in SYN-RECEIVED for a long time, they may occupy the server's half-open connection queue resources and affect normal user connections.
Common protection measures:
| Protection method | Effect |
|---|---|
| SYN Cookies | Reduce state resource usage while waiting for the third handshake |
| Limit SYN rate | Limit the number of connection requests per unit time |
| Increase appropriate queue capacity | Improve capacity to handle burst connection requests |
| Firewall and traffic scrubbing | Identify and filter abnormal connection traffic |
| Load balancing | Distribute connection establishment pressure |
On Linux, you can use the following commands to view some TCP-related configurations:
# Check whether SYN Cookies are enabled
sysctl net.ipv4.tcp_syncookies
# View SYN half-open connection queue related configuration
sysctl net.ipv4.tcp_max_syn_backlog
# View listen queue related configuration
sysctl net.core.somaxconn
Note: SYN Cookies are a resource protection mechanism and do not mean that all denial-of-service attacks can be completely eliminated.
IV. TCP Four-Way Teardown
1. Why does TCP need to release connections?
TCP is a full-duplex protocol.
After the connection is established, there are two independent data transmission directions between the client and the server:
- Client to server.
- Server to client.
Suppose the client has finished sending data, but the server still needs to continue returning data to the client.
At this point, the client can first close its sending direction while continuing to receive data from the server.
This means the two directions of TCP can be closed independently.
Therefore, when TCP releases a connection, it usually needs to close the data transmission channels in both directions separately.
This is the core reason for the four-way teardown.
2. Complete process of the four-way teardown
Assume the client actively closes the connection.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: FIN, seq=1001
Note over C: FIN-WAIT-1
S->>C: ACK, ack=1002
Note over C: FIN-WAIT-2
Note over S: CLOSE-WAIT
S->>C: FIN, seq=5001
Note over S: LAST-ACK
C->>S: ACK, ack=5002
Note over C: TIME-WAIT
Note over S: CLOSED
Note over C: Wait 2MSL, then CLOSED
The following is a step-by-step analysis.
First teardown step: Client sends FIN
The client actively calls a close operation, for example:
sock.close()
In a normal orderly close scenario, TCP sends FIN after the data to be sent has been processed.
Key fields:
FIN = 1
SEQ = 1001
Meaning:
FIN = 1: indicates that the client will no longer send new data.SEQ = 1001: the sequence number of the client's current FIN.
After the client sends FIN, it enters:
FIN-WAIT-1
This indicates that the client has initiated a close request and is waiting for the server's acknowledgment.
Note: FIN only indicates closing data transmission in the current direction; it does not mean the entire TCP connection is immediately disconnected.
Second teardown step: Server sends ACK
After the server receives the client's FIN, it returns an ACK.
Key fields:
ACK = 1
ACK_NUM = 1002
Because FIN consumes a sequence number:
ACK_NUM = FIN_SEQ + 1
= 1001 + 1
= 1002
The server confirms that the client will no longer send data.
At this point:
The client enters:
FIN-WAIT-2
The server enters:
CLOSE-WAIT
The server can still continue sending data to the client.
Third handshake: the server sends FIN
After the server finishes processing the remaining application data, it also decides to close the connection.
It then sends FIN:
FIN = 1
SEQ = 5001
The server enters:
LAST-ACK
This indicates that the server has initiated closure and is waiting for the client's final acknowledgment.
Fourth handshake: the client sends ACK
After the client receives the server's FIN, it sends an ACK:
ACK = 1
ACK_NUM = 5002
The client enters:
TIME-WAIT
After the server receives the ACK, it enters:
CLOSED
After waiting for a period of time, the client also enters:
CLOSED
At this point, the TCP connection release is complete.
3. State changes during the four-way termination handshake
| State | Trigger | Meaning |
|---|---|---|
| ESTABLISHED | Normal communication | Connection established |
| FIN-WAIT-1 | Active side sends FIN | Waiting for the peer to acknowledge the close request |
| FIN-WAIT-2 | Active side receives ACK for FIN | Waiting for the peer to send FIN |
| CLOSE-WAIT | Passive side receives FIN | Waiting for the local application to close |
| LAST-ACK | Passive side sends FIN | Waiting for the final ACK |
| TIME-WAIT | Active side receives the peer's FIN and sends ACK | Waiting for 2MSL |
| CLOSED | Connection fully released | This connection no longer exists |
State transition diagram:
flowchart TD
A["Both parties ESTABLISHED"] --> B["Active side sends FIN"]
B --> C["Active side FIN-WAIT-1"]
C --> D["Passive side receives FIN"]
D --> E["Passive side sends ACK"]
E --> F["Active side FIN-WAIT-2"]
E --> G["Passive side CLOSE-WAIT"]
G --> H["Application processes remaining data"]
H --> I["Passive side sends FIN"]
I --> J["Passive side LAST-ACK"]
J --> K["Active side receives FIN"]
K --> L["Active side sends ACK"]
L --> M["Active side TIME-WAIT"]
L --> N["Passive side receives ACK"]
N --> O["Passive side CLOSED"]
M --> P["Wait 2MSL"]
P --> Q["Active side CLOSED"]
style A fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style D fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style G fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style H fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style K fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
style N fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
style O fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style P fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style Q fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
4. Why is four-way termination needed instead of three-way?
In the three-way handshake, the server's SYN and ACK can usually be combined into one segment.
However, in four-way termination, after the server receives the client's FIN, it may not be able to immediately close its own sending direction.
This is because the server may still have data that has not been fully sent.
Therefore, the server usually needs to send an ACK first to indicate that it has received the client's close request.
After the server has finished sending its data, it then sends a separate FIN.
The process is as follows:
Client FIN
|
v
Server ACK
|
v
Server continues sending remaining data
|
v
Server FIN
|
v
Client ACK
If the server has no more data to send when it receives the FIN, then the ACK and FIN can in some cases be combined into a single segment.
Therefore, four-way termination is the typical process; it does not mean that every connection release must strictly involve four separate segments.
5. What is half-close?
TCP allows closing data transmission in only one direction.
For example:
After the client sends FIN:
- The client can no longer send new data.
- The client can still receive data from the server.
- The server can still continue sending data.
This state is called half-close.
It is useful in the following scenarios:
- After the client finishes sending a request, it notifies the server that the request data has ended.
- After the server receives the FIN, it continues processing the request.
- After the server finishes processing, it sends the result to the client.
- The server sends FIN and closes the connection.
For example, when transferring a file over TCP, the sender can notify the receiver that the file has been fully sent by closing the sending direction, while the receiver can still return a processing result.
In Python, you can use:
sock.shutdown(socket.SHUT_WR)
Where:
SHUT_RD: closes the receiving direction.SHUT_WR: closes the sending direction.SHUT_RDWR: closes both sending and receiving directions.
shutdown() and close() are not exactly the same. shutdown() is used to close a certain communication direction of the socket, while close() is used to release the socket descriptor held by the current process.
V. TIME_WAIT: Why wait after the connection is closed?
TIME_WAIT is a very important state in the TCP connection release process.
When many developers inspect Linux connections, they will find a large number of connections in:
TIME-WAIT
This does not necessarily mean that something has gone wrong with the system.
1. Where does TIME_WAIT occur?
On the side that actively closes the connection:
- Send FIN.
- Receive the peer's ACK.
- Receive the peer's FIN.
- Send the final ACK.
- Enter TIME_WAIT.
- Wait for 2MSL.
- Finally enter CLOSED.
TIME_WAIT usually occurs on the active closer.
Which end actually enters TIME_WAIT, however, depends on who actively completes the TCP close process; it is not always the client.
2. Why is TIME_WAIT needed?
TIME_WAIT mainly solves two problems.
Reason one: ensure that the final ACK can be retransmitted
Suppose the client receives the server's FIN and sends the final ACK.
But this ACK is lost in the network.
Since the server does not receive the ACK, it retransmits the FIN.
If the client had already closed the connection immediately, it would be unable to handle this retransmitted FIN correctly.
TIME_WAIT lets the client keep the connection state for a period of time.
When it receives the server's FIN again, it can resend the ACK.
sequenceDiagram
participant C as Active closer
participant S as Passive closer
C->>S: FIN
S->>C: ACK
S->>C: FIN
C->>S: ACK
Note over C: Enter TIME-WAIT
Note over S: Final ACK lost
S->>C: Retransmit FIN
C->>S: Resend ACK
Note over C: Keep waiting 2MSL
Reason two: prevent packets from the old connection from interfering with the new one
Packets in the network may arrive late because of delays.
If a connection has just been closed and a new connection is established immediately using exactly the same four-tuple, packets left over from the old connection may interfere with the new connection.
TIME_WAIT gives the old connection's packets a chance to disappear from the network, reducing the risk that historical packets affect the new connection.
3. What is MSL?
MSL stands for Maximum Segment Lifetime, which is the maximum time a segment is allowed to exist in the network.
The TCP TIME_WAIT wait time is usually:
2MSL
The 2MSL here is not simply the maximum lifetime of one segment.
It takes into account:
- Packets from the old connection may still be in transit in the network.
- The peer may retransmit the FIN.
- The local end needs an opportunity to acknowledge the FIN again.
After waiting 2MSL, packets related to the old connection generally no longer have what it takes to interfere with a new connection.
Note that MSL is a time concept in protocol design; the implementation and configuration of the TIME_WAIT timer in a specific system may differ, so you cannot simply assume that every system waits the same fixed number of seconds.
4. What should be done when there is too much TIME_WAIT?
You can check with the following command:
ss -tan state time-wait
To check the number of TIME_WAIT connections:
ss -tan state time-wait | wc -l
Common causes of many TIME_WAIT connections:
- A large number of short-lived connections.
- HTTP does not reuse connections sufficiently.
- The server frequently actively closes connections.
- The client frequently creates and destroys connections.
- The application uses short-lived TCP connections.
Common optimization methods:
| Optimization method | Description |
|---|---|
| Connection pool | Reuse TCP connections |
| HTTP Keep-Alive | Avoid establishing a new connection for every request |
| Long-lived connections | Reduce the number of connection setups and releases |
| Adjust the business communication pattern | Avoid unnecessary short-lived connections |
| Improve connection reuse | Reduce large numbers of repeated TCP handshakes |
Do not simply interpret TIME_WAIT as a system resource leak.
TIME_WAIT is a normal mechanism that TCP provides for reliable closure.
Linux has some kernel mechanisms related to TIME_WAIT reuse, but you should not solve connection-count problems by arbitrarily shortening TIME_WAIT or enabling configurations that do not suit the current scenario.
In particular, do not treat the already deprecated tcp_tw_recycle parameter as a general-purpose optimization.
VI. CLOSE_WAIT: Why does it pile up in large numbers?
Unlike TIME_WAIT, a large accumulation of CLOSE_WAIT is usually worth investigating in the application with priority.
1. What is CLOSE_WAIT?
CLOSE_WAIT means:
- The local TCP has received the peer's FIN.
- TCP has acknowledged that the peer will not send more data.
- The local application has not yet completed the close operation.
For example:
The client sends a FIN:
Client FIN
|
v
Server receives FIN
|
v
Server returns ACK
|
v
Server enters CLOSE_WAIT
At this point the server still needs to invoke the close operation before the four-way handshake can be completed.
2. Why does CLOSE_WAIT pile up?
The most common reason is that the application does not close its sockets properly.
For example:
import socket
def handle_client(conn):
data = conn.recv(1024)
# Process business data
print(data)
# If conn is not closed properly,
# CLOSE_WAIT may remain after the peer closes the connection
If an exception occurs while the program is processing business data and close() is not executed, the connection may remain in CLOSE_WAIT for a long time.
Correct approach:
import socket
def handle_client(conn):
try:
data = conn.recv(1024)
print(data)
except OSError as exc:
print(f"Socket error: {exc}")
finally:
conn.close()
In a production environment, you should also consider:
- Resource release in multithreaded and asynchronous tasks.
- Whether the connection object is held by other code.
- Whether the close operation is missed on exception paths.
- Whether there are failures when returning connections to the connection pool.
- Whether there are blocking tasks that do not exit for a long time.
3. Differences Between TIME_WAIT and CLOSE_WAIT
| Comparison Item | TIME_WAIT | CLOSE_WAIT |
|---|---|---|
| Typical Side | Active closer | Passive closer |
| Trigger Condition | Active party completes the final ACK | Receives FIN from the peer |
| Whether It Is a Normal State | Yes | Yes |
| Large Accumulation Over a Long Time | Need to evaluate the connection model | Usually requires application troubleshooting |
| Typical Cause | Many short-lived connections | Application did not close the socket |
| Main Handling Method | Connection reuse | Fix resource release logic |
VII. Other Abnormal Conditions in TCP Connection Release
1. FIN Loss
After the active closer sends a FIN, if the FIN is lost, TCP will resend the FIN according to its retransmission mechanism.
sequenceDiagram
participant C as Active closer
participant S as Passive closer
C->>S: FIN
Note over S: FIN lost
Note over C: Waiting for timeout
C->>S: Retransmit FIN
S->>C: ACK
S->>C: FIN
C->>S: ACK
Note over C: Enter TIME-WAIT
If no response is received for a prolonged period, the connection close may eventually time out.
2. Last ACK Loss
After the client sends the last ACK, it enters TIME_WAIT.