This is a network programming interview key points of knowledge, summed up: to establish a connection-three times handshake
TCP establishes a connection between the server and the client through a three-time handshake.
The so-called three-time handshake (three-way handshake) means that when a TCP connection is established, the client and server are required to send a total of 3 packets.
The purpose of the three-time handshake is to connect the server to the specified port, establish a TCP connection, and synchronize the serial number and confirmation number of both parties and Exchange TCP window size information.
In socket programming, the server first calls the socket, bind, listen, and accept, and blocks the accept, triggering three handshake processes when the client calls connect.
First handshake: The client calls connect to send a SYN packet to the server and enters the syn_sent state, waiting for the server to confirm;
Second handshake: The server receives a SYN packet from the client, must send back a confirmation packet (ACK) answer, and also sends a SYN packet to the client, at which time the server enters the SYN_RCVD state;
Third handshake: After the client receives the data from the server, connect returns, enters the established state, and sends back the acknowledgement packet ack to the server, and the server receives this ACK after accept returns, also enters the established state.
At this point, the three-time handshake is complete, and the server and the client establish a connection. The above process is illustrated as follows:
terminating the connection--four-time handshake
TCP Terminates the connection between the server and the client through a four-time handshake, which requires sending four packets altogether.
First handshake: Client or server call close initiates an active shutdown, we use the client as an example, the client sends a fin to the server and enters the fin_wait_1 State;
Second handshake: The server sends a confirmation packet ack to the client after receiving FIN, and enters the close_wait state, the client receives an ACK and enters the fin_wait_2 state;
Third handshake: After a period of time, the server is ready to close the connection, and then call Close (the code is active or called by the kernel) to send a fin to the client, and enter the Last_ack State;
Fourth handshake: The client receives the server's fin after sending an ACK to the server, then enters the time_wait state, and the server receives this ACK after it enters the closed state.
This four-time handshake completes, the connection between the client and the server is terminated, as shown below (left client, right server):