Sub topic 2
Checksums, TCP Handshakes, and Reliable Streams
Assume you understand IP addresses, packets, and the layered network model. This chapter focuses on how TCP detects errors, opens connections, delivers bytes reliably, and differs from message-based protocols.
Checksums and error detection
A checksum is a value calculated from a packet’s contents. The sender places it in the transport header. The receiver calculates the value again and compares it. A mismatch means that bits probably changed in transit, so the receiver discards the segment or datagram.
TCP and UDP checksums cover the transport header, payload, and a small IP-derived pseudo-header. This helps detect delivery to the wrong address or protocol. A checksum detects many accidental errors, but it does not correct them and is not a security mechanism.
| Protocol | Error response |
|---|---|
| UDP | Discards an invalid datagram; the application must handle missing data |
| TCP | Discards invalid data and relies on retransmission |
TCP segments and the TCP header
TCP divides a byte stream into segments. Each segment includes source and destination ports, sequence and acknowledgment numbers, flags, a receive window, a checksum, and optional fields such as maximum segment size.
The sequence number identifies the position of the segment’s first payload byte. The acknowledgment number reports the next byte the receiver expects. Flags include SYN for opening, ACK for valid acknowledgments, FIN for orderly closing, and RST for immediate reset.
Opening a connection: the three-way handshake
TCP uses three messages:
The handshake synchronizes initial sequence numbers and confirms that both directions work. It also allows each endpoint to advertise connection parameters.
How TCP delivers data reliably and in order
TCP numbers bytes, not packets. The receiver acknowledges received bytes. If a segment is lost, its missing sequence range remains unacknowledged. TCP retransmits after a timeout and may retransmit sooner after duplicate acknowledgments. The receiver reorders segments and gives the application an ordered stream.
Byte stream versus message boundaries
TCP preserves byte order but does not preserve application write boundaries. Two writes may arrive in one recv call, or one write may require several calls. Applications that need messages must add framing, such as a length prefix or delimiter.
> callout note > Always loop on recv. Treat an empty result as an orderly peer close, not as a complete application message.
Exercise
A program sends b"one" and then b"two" over TCP. What might one recv call return?
Show answer
It might return b"onetwo", only part of one write, or another grouping. TCP provides a byte stream, not message boundaries.