Sub topic 1
Where the transport and application layers sit
Prerequisites
This chapter assumes you know the four-layer model (application, transport, network, link), the terms bandwidth and round-trip time (RTT), and basic Python. The later chapters build on the ideas here.
Layers and their roles
The application layer holds programs such as browsers and mail clients. The transport layer sits below it and delivers data between two processes on different hosts. The network layer moves packets between hosts, and the link layer moves frames across one hop.
Sockets and ports
A socket is a program's endpoint for network communication. A socket is identified by an IP address and a port number. A port is a 16-bit number from 0 to 65535. A TCP connection is identified by four values: the local and remote IP addresses and the local and remote ports.
A TCP client creates a socket and calls connect. A TCP server creates a socket, calls bind and listen, and then calls accept.
import socket
with socket.create_connection(("example.com", 80)) as s:
s.sendall(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
print(s.recv(200))The function create_connection creates the socket and calls connect, which starts the TCP handshake.
UDP
UDP (User Datagram Protocol) is a connectionless transport. It adds ports and a checksum and nothing more. It has no handshake, no acknowledgements, and no retransmission. The sender cannot tell whether a datagram arrived. UDP suits DNS queries and live video, where delay matters more than reliability.
The TCP segment
TCP (Transmission Control Protocol) sends data as segments. Each segment carries a sequence number, which is the byte offset of its first data byte. It also carries an acknowledgement number, which is the next byte the receiver expects. Sequence numbers count bytes, not segments. The header also has flags such as SYN, ACK, and FIN.
Opening and closing a connection
The three-way handshake works as follows:
| Step | Direction | Flags | Sequence number | Acknowledgement number |
|---|---|---|---|---|
| 1 | Client to server | SYN | x | none |
| 2 | Server to client | SYN, ACK | y | x + 1 |
| 3 | Client to server | ACK | x + 1 | y + 1 |
Closing uses FIN segments. Each side sends a FIN, and the other side replies with an ACK.
Reliable delivery
The sender starts a timer when it sends a segment. If the acknowledgement does not arrive before the timer expires, the sender retransmits. The timeout comes from RTT estimates. Fast retransmit is faster: three duplicate ACKs for the same byte signal a lost segment, so the sender resends it without waiting for the timer.
Exercise
Exercise
A client sends a SYN with sequence number 500. The server replies with SYN-ACK, sequence number 900. What acknowledgement number does the client send in its final ACK, and what acknowledgement number does the server's SYN-ACK carry?
Show answer
The server's SYN-ACK carries acknowledgement number 501. The client's final ACK carries acknowledgement number 901.