Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 79 ยท Transport Layer

TCP Segments and the Three-Way Handshake

Read every field of the TCP header, see how sequence and acknowledgment numbers work, follow SYN, SYN-ACK and ACK, and learn how a SYN flood attacks the handshake.

UDP sends independent datagrams and does not care what happens to them. Most applications want something stronger: a reliable, ordered stream of bytes, like a pipe between two programs. TCP (Transmission Control Protocol) builds that pipe on top of unreliable IP packets. It does so by adding sequence numbers, acknowledgments, timers and a window, all carried in a small header in front of your data.

In this lesson you learn the layout of that header, what sequence and acknowledgment numbers really count, and how two hosts agree on a connection with the three-way handshake. You will parse a real TCP header from raw bytes, replay a handshake with exact numbers, and watch a SYN flood fill a server's queue. Reliability, flow control and congestion control each get their own lesson after this one.

The unit of TCP: the segment

Applications hand TCP a stream of bytes, with no message boundaries. TCP chops that stream into chunks called segments, and each segment travels as the payload of one IP packet. The largest chunk of data that fits in a segment is the Maximum Segment Size (MSS). On Ethernet with a 1,500-byte MTU, an IPv4 packet has a 20-byte IP header and a 20-byte TCP header, so the usual MSS is 1,500 - 40 = 1,460 bytes. The two ends announce their MSS during the handshake, and each sends segments no larger than what the other can accept.

flowchart LR
    A["Application bytes<br/>(a stream)"] --> T["TCP: cut into segments<br/>each at most one MSS"]
    T --> I["IP: one packet per segment"]
    I --> E["Ethernet frame"]

TCP turns a byte stream into segments; each segment rides inside an IP packet and then a frame.

The TCP header, field by field

The fixed part of a TCP header is 20 bytes. All numbers are big-endian ("network byte order").

Field Size Meaning
Source port 16 bits The sender's port.
Destination port 16 bits The receiver's port, such as 80 or 443.
Sequence number 32 bits Position, in the sender's byte stream, of the first data byte in this segment (or the ISN on a SYN).
Acknowledgment number 32 bits The next sequence number the sender of this segment expects to receive. Valid only if the ACK flag is set.
Data offset 4 bits Header length in 32-bit words (5 to 15, so 20 to 60 bytes).
Reserved 4 bits Must be zero.
Flags 8 bits CWR, ECE, URG, ACK, PSH, RST, SYN, FIN.
Window 16 bits How many more bytes the sender of this segment is willing to receive (see flow control).
Checksum 16 bits Covers header, data and a "pseudo-header" with the IP addresses.
Urgent pointer 16 bits Used with the URG flag; rarely used today.
Options 0 to 40 bytes MSS, window scale, SACK, timestamps and more.

Unlike UDP, TCP has no length field. The receiver gets the segment length from the IP header and subtracts the IP and TCP header sizes.

The flags

Each flag is one bit. The ones you will meet constantly:

  • SYN (synchronize): starts a connection and carries the initial sequence number.
  • ACK: the acknowledgment number field is valid. Set on every segment after the first SYN.
  • FIN: the sender has no more data. Used to close, covered in the next lesson.
  • RST: reset. Abort the connection immediately, for example when a segment arrives for a port nobody is listening on.
  • PSH: asks the receiver to deliver buffered data to the application now instead of waiting for more.
  • URG: the urgent pointer is valid (almost never used).
  • ECE and CWR: congestion signalling bits used with ECN (see congestion control).

The checksum and the pseudo-header

The TCP checksum is the same 16-bit ones' complement sum used for IPv4 headers, but it covers the TCP header, the data, and a pseudo-header made of the source IP, destination IP, a zero byte, the protocol number (6) and the TCP length. Including the addresses lets the receiver detect a segment that was delivered to the wrong host even though the IP header was repaired along the way.

Reading a header from raw bytes

The example below builds a SYN segment like the one a Linux client sends when it opens a connection. It includes the usual options, parses the bytes back into fields, and verifies the checksum with its pseudo-header.

Python Build and parse a TCP SYN segment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the output: the header is 40 bytes (data offset 10), the flags show only SYN, the acknowledgment number is 0 because the ACK flag is off, and the options announce what this host supports.

Sequence and acknowledgment numbers

TCP numbers bytes, not segments. Each direction of a connection has its own sequence space, which starts at a number called the initial sequence number (ISN). The ISN is chosen unpredictably, not 0 or 1. If every connection started at 0, a delayed duplicate segment from an old connection could be mistaken for part of a new one, and an attacker who could guess the numbers could forge segments.

The rules are short:

  • The sequence number of a segment is the number of its first data byte. A segment carrying 100 bytes with sequence 5,000 covers bytes 5,000 to 5,099.
  • The acknowledgment number is the sequence number of the next byte the receiver wants. Acking 5,100 means "I have everything before 5,100".
  • A SYN and a FIN each consume one sequence number, even though they carry no data. That is why the ACK of a SYN is ISN + 1.
  • Pure ACKs (no data, no SYN, no FIN) consume nothing.

Sequence numbers are 32 bits and wrap around. Comparisons use modular arithmetic, so "later" means "within half the number space ahead".

The three-way handshake

Before data can flow, both sides must agree that a connection exists, choose their ISNs, and exchange their options. That takes three segments:

sequenceDiagram
    participant C as Client
    participant S as Server
    Note over S: LISTEN
    C->>S: SYN, seq = x
    Note over C: SYN-SENT
    S->>C: SYN+ACK, seq = y, ack = x + 1
    Note over S: SYN-RECEIVED
    C->>S: ACK, seq = x + 1, ack = y + 1
    Note over C,S: ESTABLISHED

Each side's SYN is acknowledged by the other side. The middle segment carries both, so three segments are enough instead of four.

  1. SYN. The client picks an ISN x and sends a segment with SYN set. It also lists its MSS, window scale and other options.
  2. SYN-ACK. The server, which is in the LISTEN state, picks its own ISN y, acknowledges x + 1, and sends its own options. Options that only work if both sides offer them (window scaling, SACK, timestamps) are in use only when they appear in both SYNs.
  3. ACK. The client acknowledges y + 1. The connection is now ESTABLISHED on the client, and on the server as soon as this segment arrives. The client may put application data in this very segment or straight after it.

The handshake costs one round trip before the first byte of data can be sent, which is why connection reuse, TLS 1.3 and QUIC all work hard to avoid repeating it.

Python Replay a handshake and the first data exchange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two directions are independent. The client's numbers only grow when the client sends, and the server's only when the server sends. The ISN plus one SYN is the reason the byte counts above subtract 1.

Simultaneous open and half-open connections

Two hosts can send SYNs to each other at the same moment (a simultaneous open); TCP handles it with four segments and both sides end up ESTABLISHED. It is rare in practice. A more common oddity is a half-open connection: one host crashes or loses its state while the other still believes the connection is alive. When the surviving host sends data, the rebooted one has no matching connection and answers with RST, which tears the stale connection down.

SYN floods

In the handshake, the server must remember something after it sends the SYN-ACK: the client's ISN, the options, the address and port. This state sits in a queue of half-open connections (SYN-RECEIVED) until the final ACK arrives or a timer expires. The queue has a finite size.

In a SYN flood attacker sends huge numbers of SYNs, usually with spoofed source addresses. The server answers each one and holds a queue entry, and the final ACK never comes, because the spoofed hosts never sent a SYN. Once the queue is full, genuine clients get no answer. The attacker spends little: a SYN is a tiny packet and the attacker never keeps state.

The standard defense is SYN cookies. When the queue is under pressure, the server stops storing state. It encodes what it needs (a hash of the addresses, ports and a secret and timestamp, plus a few bits for the MSS) into the server's initial sequence number in the SYN-ACK. A real client answers with ACK = that number + 1, so the server can recompute the hash, check it, and rebuild the connection from the ACK alone. Spoofed senders never reply, so they cost the server nothing. Other measures include a larger backlog, shorter SYN-RECEIVED timeouts and filtering upstream. More on this family of attacks is in common attacks and how to defend.

Python A SYN flood fills the backlog; SYN cookies survive it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Options you should recognize

The options area is where TCP evolves without changing the fixed header. These appear in almost every SYN:

Option Kind Purpose
End of list 0 Stops option parsing.
NOP 1 One byte of padding to align the next option.
MSS 2 Largest segment the sender can receive (SYN only).
Window scale 3 Shift count that multiplies the 16-bit window (SYN only; see flow control).
SACK permitted 4 Allows selective acknowledgments (see reliability).
SACK 5 Lists received byte ranges after a gap.
Timestamps 8 Helps measure round-trip time and protect against wrapped sequence numbers.

Because options are announced in the SYN, a middlebox that strips or rewrites them silently changes how a connection performs. A firewall that "cleans" the window scale option, for example, can cap throughput on fast links.

When you capture a handshake in Wireshark, the displayed sequence numbers are relative (starting at 0) by default. The raw values on the wire are the large random ISNs, as in the examples above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends a SYN with sequence number 4,000. What acknowledgment number does the server's SYN-ACK carry?

    A SYN consumes one sequence number, so the server acknowledges the next byte it expects: 4,000 + 1 = 4,001.
  2. 2. A segment has sequence number 9,000 and carries 250 bytes of data. What does a receiver that got it correctly, and everything before it, acknowledge?

    The segment covers bytes 9,000 to 9,249, so the next expected byte is 9,250. The acknowledgment number names the next byte wanted.
  3. 3. What is the usual MSS on an Ethernet path with MTU 1,500 using plain IPv4 and TCP headers?

    MSS is the MTU minus the 20-byte IP header and the 20-byte TCP header: 1,500 - 40 = 1,460 bytes of data.
  4. 4. Why does a SYN flood hurt a server that has no SYN cookies?

    The server keeps state for every SYN-RECEIVED connection until the third ACK or a timeout. Spoofed SYNs never complete, so the queue fills and real clients are refused.
  5. 5. Which statement about TCP's header is true?

    TCP has no length field (the length comes from IP). Data offset counts 32-bit words, the checksum covers header, data and a pseudo-header, and the window field is 16 bits.

Summary

  • TCP cuts a byte stream into segments of at most one MSS (1,460 bytes on typical Ethernet) and numbers every byte.
  • The header has ports, 32-bit sequence and acknowledgment numbers, a data offset, flags (SYN, ACK, FIN, RST, PSH, ...), a 16-bit window, a checksum with a pseudo-header, and options.
  • The acknowledgment number is the next byte expected. SYN and FIN each use one sequence number.
  • The three-way handshake (SYN, SYN-ACK, ACK) exchanges ISNs and options and costs one round trip.
  • A SYN flood fills the half-open queue with spoofed SYNs; SYN cookies defend by encoding the state into the server's ISN.

Next, learn how connections end and which states they pass through in TCP connection teardown and the state machine.