Coder's Cat

TCP 3 Way Handshake In Detail

2020-03-10

file:img/CAPTURE-2020_03_10_tcp-connection-3-handshake.org_20200310_113856.png

TCP is a connection-oriented protocol and provides reliable communication. Before TCP transmits data, it will use the three-way handshake to establish a connection.

Why we need a 3-way handshake

Suppose Alice and Bob want to talk on a phone. During the old days. The connection is not stable. Before Alice and Bob begin to talk with each other, they want to have a double-check about the connectivity.

So, this is the typical starting:

file:img/tcp-handshake.png

Similarly, TCP’s 3-way handshake is the process of exchanging some data to make sure two things:

  • Sending data from client to server is OK
  • Sending data from server to client is OK

The process

The overall process of 3-way handshake is:

file:img/tcp-3-handshake-process.png

SYN means synchronization of the sequence numbers. Client and server communicate each other their initial sequence numbers which are crucial for the communication to start.

Note: The peer must acknowledge all the TCP segments which consume sequence numbers. If no acknowledgment is received for this segment, it will be retransmitted until it reaches the specified number of times.

It is a crucial reason that TCP could provide reliable data transmission.

What is ack/syn?

ack and syn are both flag bits of TCP header:

file:img/CAPTURE-2020_03_10_tcp-connection-3-handshake.org_20200310_131301.png

The sequence number and acknowledgment number are both 32 bits.

How the initial sequence number is generated?

Initial Sequence Number (aka ISN) does not start from 0, and both parties of the communication generate it separately.

Why ISN cannot be a fixed number?

  • For security. If the ISN of a connection is known, it is easy for an attacker to construct a sequence number. The source IP and source port numbers are easy to forge. In this way, an attacker can forge an RST packet and force the connection to close.
  • A dynamically growing ISN can guarantee that segments in the right order.

What will happen if the client sends ack, but the server does not respond?

Defaultly, client will retry in 2 seconds, then 4 second, then 8 seconds … until it tried 6 times. This number is configured by /proc/sys/net/ipv4/tcp_syn_retries.

What else

file:img/CAPTURE-2020_03_10_tcp-connection-3-handshake.org_20200310_171943.png

From the captured result by Wireshark. Except for SYN, ACK, Sequence number, there are some other parameters contained.

MSS (Maximum Segment Size), here client’s MSS is 1460 and server’s MSS is 1360.

WS (Windows Scaling)=, which used to control the maximum TCP receive window size, more details please refer to RFC1323.

There are more parameters. They are essential configuration parameters for both sides to know before TCP transmission start.

Join my Email List for more insights, It's Free!😋