knowledge

Lecture 6

The Transport Layer

The network, data link and physical layers carry packets end to end.Packets can be lost through bit errors at the physical layer, or through buffer overflows at routers and switches.They can also be reordered, because they follow different paths.

The transport layer makes these services available to programs.It runs only in end systems.Routers never run it when they forward packets.

UDP (User Datagram Protocol) takes no action on loss or reordering.TCP (Transmission Control Protocol) detects and repairs both.

Server. A server is the role of a program that waits for requests.

Client. A client is the role of a program that initiates communication.

Colloquially, a server is also a machine that hosts resources.The transport layer uses the word only for the role.

Port numbers are 16-bit unsigned integers, from 0 to 65 535.The operating system assigns them statically or dynamically.

A server usually has a static, well-known port, such as 53 for DNS or 80 for HTTP.Clients must know this port in advance.The file /etc/services lists the standard ones.A home-made client-server application picks its own server port and codes it into the application.

Ephemeral port. An ephemeral port is a dynamically assigned port.The operating system picks it for a client, usually above 1024.

The destination port of a DNS query selects the DNS server process.The source port matters only for the response:the server sends it from port 53 back to the client's ephemeral port.

UDP

Datagram. A datagram is the UDP unit: a UDP header and one message.

UDP keeps no connection state between the sender and the receiver.Datagrams can arrive out of order or be lost.The application handles these cases if it needs to.For example, a DNS client resends its query if no answer comes in time.

UDP preserves message boundaries.The receiver gets the exact datagram or nothing.

IP header, protocol = UDPsource portdestination portlengthchecksumpayload (data)UDP header,8 bytesUDP datagram= IP data32 bits
A UDP datagram inside an IP packet, 32 bits per row.

The 16-bit length field counts the 8-byte header and the payload, so a datagram holds at most 65 535 bytes.That is far more than the MTU of most links.

IP Fragmentation

Path MTU (PMTU). The path MTU is the smallest link MTU along a path.

Fragment. A fragment is an IP packet with one piece of a larger payload.Each fragment has its own IP header and fits the path MTU.

If a packet exceeds the path MTU, the IP layer of the source cuts it into fragments.Only the destination reassembles them, never a router.UDP never sees the split, so it still delivers whole messages.

Three IPv4 header fields describe a fragment.

  • Identification. The source gives all fragments of a packet the same identification number.
  • More Fragments (MF) flag. MF is 1 in every fragment except the last.
  • Fragment offset. The offset is the position of the fragment's data in the original payload, in units of 8 bytes.So every fragment except the last carries a multiple of 8 bytes.

IPv6 moves the same three fields into a Fragment extension header (Next Header 44).Its identification has 32 bits.Routers never fragment IPv6 packets: only the source does.

Example 1. Fragmenting a UDP datagram.

An application sends 4000 bytes over UDP and IPv4.The source already knows the path MTU, 1500 bytes.

  1. The 8-byte UDP header gives a datagram of 4000+8=40084000 + 8 = 4008 bytes.
  2. The 20-byte IPv4 header gives a packet of 4008+20=40284008 + 20 = 4028 bytes.
  3. Each fragment carries at most 1500−20=14801500 - 20 = 1480 bytes of payload.This is a multiple of 8, so it is the fragment size.
  4. Two full fragments leave 4008−2×1480=10484008 - 2 \times 1480 = 1048 bytes.With its IPv4 header, the last fragment has 1048+20=10681048 + 20 = 1068 bytes.
IPv4 fieldOriginal packetFragment 1Fragment 2Fragment 3
Total length (bytes)4028150015001068
Identification567567567567
MF flag0110
Fragment offset00185370
8 × offset (bytes)0014802960
fragment 1IP header20 bytesUDP header8 bytes1472 bytesof the messagefragment 2IP header20 bytes1480 bytesof the messagefragment 3IP header20 bytes1048 bytesof the message
The three fragments of Example 1. Green: bytes of the message.

Only fragment 1 carries the UDP header, so the ports appear in only one of the three packets.

If one fragment is lost, reassembly never completes, and the destination discards the whole 4000-byte message.With nn fragments, each lost with probability pp, the message survives with probability (1−p)n(1-p)^n.

Path MTU Discovery

PMTUD (Path MTU Discovery). PMTUD relies on ICMP errors.The routers tell the sender that a packet is too big.RFC 1191 specifies PMTUD for IPv4, and RFC 8201 for IPv6.

  1. In IPv4, the sender sets the DF (Don't Fragment) flag.In IPv6, it just sends, because routers never fragment.
  2. If a packet exceeds the MTU of the next link, the router drops it.It returns an ICMP "Fragmentation Needed" in IPv4, or an ICMPv6 "Packet Too Big" in IPv6.
  3. The sender lowers its path MTU estimate and sends smaller packets.

PMTUD works only if the ICMP message reaches the sender.

PLPMTUD (Packetization-Layer PMTUD). PLPMTUD relies on probes.The sender finds the PMTU itself, with no help from the routers.RFC 8899 specifies PLPMTUD.

  1. The sender starts from a packet size known or expected to work:at least 1280 bytes in IPv6, and at least 576 bytes in IPv4.
  2. It sends probe packets of selected larger sizes.
  3. End-to-end feedback says whether each probe arrived.
  4. If larger probes succeed, the sender raises its estimate.If they fail, it lowers the estimate or stops raising it.

The feedback comes from the packetization layer.This layer is the protocol that cuts the data into packets.Over TCP, the feedback is the TCP ACKs.Over UDP, it is the acknowledgements of the protocol or the application.

The UDP Checksum

The UDP checksum covers the header, payload and a pseudo-header.

Pseudo-header. The pseudo-header is a set of IP-layer fields.It holds the source and destination addresses, the payload length and the protocol number.

The checksum therefore protects the IP addresses as well as the data.

In IPv4, the UDP checksum is optional but recommended.A sender that does not compute it writes zero in the field.This was a concession to the cost of the computation on 1980s hosts.It relied on link-layer error detection, such as the Ethernet FCS, to catch most corruption.RFC 1122 recommends enabling it, and in practice hosts do.

In IPv6, the UDP checksum is mandatory.A receiver discards a UDP datagram that arrives with a zero checksum.Only some tunnel protocols may send a zero checksum, under the conditions of RFC 6935 and RFC 6936.

IPv6 removed the IP header checksum, because it cost every router work on every packet.The argument was that link-layer checks already protect each hop.This protection, however, is recomputed at every hop, so it misses corruption inside a router.The UDP checksum is therefore the only end-to-end check left, and the only end-to-end check on the IP addresses.

UDP Sockets

Programs use UDP through the socket interface.In Unix, a socket behaves like a file for reading and writing.

File descriptor. A file descriptor is an integer that names an open file.

CallDoes
socket()creates an IPv4 socket with AF_INET,
or an IPv6 socket with AF_INET6
bind()associates a local IP address and port with the socket
sendto()sends one message to a destination IP address and port
recvfrom()blocks until a message arrives for the socket's port;
returns it with its source IP address and port
close()releases the socket

The operating system names each new socket by a file descriptor.In Python, socket.socket() returns a socket object that holds it.The program calls the other functions as methods of this object.

bind() accepts two wildcards.Port 0 means any free port.The address 0.0.0.0 or :: means all IP addresses of the host.A client usually skips bind().It then gets an ephemeral port and the preferred IP address of the operating system.

Example 2. A UDP client and server.

The server waits on port 5000 and displays the client's message.

# server
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 5000))
data, addr = s.recvfrom(4096)
print(data.decode())
 
# client
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b"Networks are great!", ("192.0.2.10", 5000))
s.close()

There is no UDPv6 or TCPv6.One UDP and one TCP carry the same headers over both IP versions.A socket, however, is either IPv4 or IPv6, unless it supports both.getaddrinfo() asks DNS for the addresses of a name, so the application opens a socket of a version that the destination has.

>>> socket.getaddrinfo("nal.epfl.ch", None)
[(AF_INET6, ..., ('2001:620:618:521:1:80b3:2127:1', 0, 0, 0)),
 (AF_INET, ..., ('128.179.33.39', 0))]

Dual-Stack Sockets

Dual-stack socket. A dual-stack IPv6 socket also receives IPv4 packets.It is bound to both the IPv6 and the IPv4 addresses of its host.

IPv4-mapped IPv6 address. This IPv6 address embeds an IPv4 address.It is the prefix ::ffff:0:0/96 followed by the IPv4 address.This mapping is a stateless translation.

A dual-stack socket names each IPv4 correspondent by this address.

2001:face:b00c::1IPv6 host1.2.3.4IPv4 host2001:baba::b0b0local IPv6 address11.22.33.44local IPv4 addressIPv6 socketdual-stackapplicationrecvfrom() reports2001:face:b00c::1recvfrom() reports::ffff:0102:0304over IPv6over IPv4
One dual-stack IPv6 socket. Solid: the IPv6 path. Dashed: the IPv4 path.

Linux makes IPv6 sockets dual-stack by default.In Windows, each socket must enable it with setsockopt().

An IPv4 socket cannot be dual-stack.IPv4 addresses map into a subset of the IPv6 space, because IPv6 addresses are longer.The converse is impossible: IPv6 has more addresses than IPv4.So an IPv4 socket cannot receive data from an IPv6 address.

Delivering Datagrams to Sockets

A UDP socket is identified by its local IP address and port.It is bound to one port and to one or more local IP addresses.The operating system delivers each datagram to the socket bound to the datagram's destination IP address and destination port.

Send buffer. The send buffer of a socket holds data not yet sent.

Receive buffer. The receive buffer of a socket holds data not yet read.

The operating system sends a datagram as soon as possible.It keeps the datagram in the send buffer only while the interface is busy.On the receiving side, the IP layer first reassembles the fragments.The datagram is then consumed when the application reads it, or dropped if the receive buffer overflows.

Example 3. Which socket receives the datagram?

An application has three UDP sockets.

SocketVersionLocal addressPort
5IPv62001:baba::b0b032456
3IPv411.22.33.4432456
4IPv411.22.33.4432654

A datagram to 11.22.33.44, port 32456, goes to socket 3.Sockets 5 and 3 share a port but not an address.Sockets 3 and 4 share an address but not a port.

Now let socket 5 be dual-stack and bound to every local address on port 32456.Socket 3 is then unnecessary.Socket 5 receives the datagrams to 2001:baba::b0b0 and to 11.22.33.44 on port 32456, with one pair of buffers for both addresses.

TCP: A Reliable Byte Stream

TCP delivers all data in order and without loss, unless the connection breaks.

Byte stream. A byte stream is an ordered sequence of bytes.It has no message boundaries.TCP carries each direction of a connection as one byte stream.

TCP is therefore a streaming service.Several small writes at A can reach B as one segment, and one write can reach B as several segments.So applications group the bytes into messages themselves.

TCP cuts the byte stream into segments.Each segment carries a TCP header and a piece of the stream.

MSS (Maximum Segment Size). The MSS is the largest TCP payload.

TCP, not the application or IP, decides how to cut the data.It knows the allowable MSS and cuts every segment to fit, so it avoids fragmentation at the IP layer.

Sequence Numbers and Acknowledgements

TCP numbers every byte of the stream.

Sequence number. This number names the first byte of a segment.

Acknowledgement number. This number names the next expected byte.It is cumulative: ack 8501 confirms every byte up to 8500.

In TCP, an ACK is a segment with the ACK flag set.Its acknowledgement number is then valid.

A range of bytes such as 8001:8500 includes both of its ends.After bytes 8001:8500 arrive in order, the receiver answers ack 8501.

The TCP Buffers

In TCP, data waits in the send buffer until TCP creates a segment and the IP interface is ready.

Retransmission buffer. The retransmission buffer holds sent bytes.TCP keeps them until the receiver acknowledges them.

In TCP, the receive buffer is also called the re-sequencing buffer.It stores out-of-order data until the gaps before it are filled.This data is invisible to the application.Bytes leave the receive buffer only when they are in order and the application reads them, at its own pace.

Retransmission After a Timeout

Timeout. A timeout is the expiry of the timer started for a segment.If no ACK covers the segment in time, the sender resends it.

Example 4. Losses repaired by a timeout.

The application at A writes 500-byte blocks at a slow pace, so TCP sends 500-byte segments.The data segments of lines 3 and 4 are lost, and so is the ACK of line 7.

AsenderBreceivertime1delivers 8001:8500seq 8001:85002ack 85013seq 8501:90004seq 9001:95005stores 9501:10000seq 9501:1000067ack 85018delivers 8501:9000seq 8501:90009ack 900110delivers 9001:10000seq 9001:9500timeout
Example 4. Solid green: a segment that consumes sequence numbers. Dashed: an ACK without data. A cross marks a loss.

At line 10, bytes 9001:9500 fill the last gap.B then delivers them with the bytes 9501:10000 that it stored at line 5.

Selective Acknowledgement

The acknowledgement number hides the bytes after a gap, so the sender may resend data that B already has.

SACK (Selective Acknowledgement). SACK confirms data after a gap.It is a TCP option that holds up to 3 blocks.The sender then retransmits only the missing bytes.

Most TCP implementations use SACK.A SACK block ends with the byte after its last byte, like an acknowledgement number.So sack 9501:10001 reports bytes 9501:10000.

Duplicate ACK. A duplicate ACK repeats the previous ACK.It carries the same acknowledgement number.

Data after a gap produces duplicate ACKs.By default, 3 duplicate ACKs trigger a retransmission before the timeout.

Optimized segmentation. TCP merges waiting blocks into one segment.The blocks come from the application and fit in one MSS together.

Example 5. SACK and a merged segment.

The application at A writes 500-byte blocks, and the MSS is 1000 bytes.The application writes the first four blocks one at a time, so TCP sends them in four separate segments.The segments of lines 3 and 4 are lost.To keep the example short, A retransmits after one duplicate ACK.

AsenderBreceivertime1delivers 8001:8500seq 8001:85002ack 85013seq 8501:90004seq 9001:95005stores 9501:10000seq 9501:1000067ack 8501, sack 9501:100018MSS = 1000 bytesdelivers 8501:10000seq 8501:95009ack 1000110delivers 10001:10500seq 10001:10500
Example 5, with the hues of Example 4.

At line 8, both missing blocks wait in the retransmission buffer.Together they fit in one MSS, so A resends them in one segment.

At line 5, B stores bytes 9501:10000 but hides them from the application, because bytes 8501:9500 are still missing.

8001:8500 arrives8001:8500can be read9501:10000 arrives8001:8500can be read8501:9500missing9501:10000invisible tothe application8501:9500 arrives8001:10000can be read
The receive buffer of B in Example 5, in 500-byte blocks.

The Sliding Window

If one segment stays lost while the sender keeps sending, the later segments pile up in the receive buffer until it overflows.

AsenderBreceivertimesegment 01segment 112segment 212nsegment nsegment 0 again12nn+1segment n+1
Segment 0 hangs while the sender keeps sending, with the hues of Example 4. Boxes: the segments in the receive buffer.

Sliding window. The sliding window is a range of sequence numbers.The sender may have data in flight only inside this range.Data is in flight when it is sent but not yet acknowledged.

Its lower edge is the smallest unacknowledged sequence number.Its upper edge is the lower edge plus the window size.The sender sends the data inside the window as soon as the socket holds it.

Usable window. The usable window is the unsent part of the window.

0123456789101112lower window edgeupper window edge = lower edge + window sizeacknowledgedsent, notacknowledgedusablewindowoutside the windowwindow size: 4000 bytes
The sender's sequence numbers, in segments of 1000 bytes.

Each new acknowledgement number moves both edges, so the window slides.

The window examples number segments instead of bytes.S = n means that the sender sends segment nn.A = n means that an ACK confirms all segments up to and including nn.So nn is the last confirmed segment, not the next expected one.

Example 6. A 4000-byte window.

Each segment carries 1000 bytes, so the window spans 4 segments.

EventWindowUsable window
start0–30–3
S = 00–31–3
A = 01–41–4
S = 1, S = 21–43–4
S = 3, A = 12–54–5
S = 4, S = 52–5none
A = 23–66
S = 6, A = 34–77
S = 7, A = 45–88
S = 8, A = 56–99
S = 9, A = 67–1010
S = 10, A = 78–1111

At the start, the socket holds only segment 0, so the sender sends nothing else.

The retransmission buffer has the size of the window.SACK lets the sender leave SACKed data out of its retransmissions.RFC 2018 still lets a receiver discard data that it SACKed, so the sender keeps it until the acknowledgement number covers it.

Example 7. A SACK does not slide the window.

The window is 4000 bytes, with 1000-byte segments.The sender sends segments 0 to 3, and segment 0 is lost.The receiver sends A = −1 with SACK 1, then SACK 1–2, then SACK 1–3.

The sender cannot send segment 4.The acknowledgement A = −1 confirms none of the segments 0 to 3, so the lower edge stays at segment 0.SACK confirms segments 1 to 3 but leaves the window at 0–3.Segment 4 waits until segment 0 is retransmitted and acknowledged.

EventRetransmission bufferReceive buffer
SACK 1–3 arrives0, 1, 2, 31, 2, 3
S = 0 resent0, 1, 2, 30, 1, 2, 3, in order
A = 3 arrivesempty0, 1, 2, 3
application reads 0–3emptyempty
S = 444

Flow Control

A fixed window still lets a slow reader overflow the receive buffer.The window limits unacknowledged data, but acknowledged data stays in the buffer until the application reads it.

Example 8. A fixed window and a slow reader.

The window spans 4 segments of 1000 bytes.The receiver acknowledges each segment when it arrives, but its application reads nothing.

EventWindowReceive buffer
S = 0 to 30–30–3
A = 0 to 34–70–3
S = 4 to 74–70–7
A = 4 to 78–110–7
S = 8 to 118–110–11

Every ACK slides the window, although the application has read nothing.So the buffer outgrows the window and finally overflows.

Flow control. With flow control, the receiver sets the window size.It advertises its free buffer space in every segment.

The sender sets its window to the advertised value.If the buffer is full, the receiver advertises a window of 0.

Flow control adapts the sender's rate to the receiver's reading speed.Congestion control, by contrast, adapts it to the network.

Example 9. Flow control with a slow reader.

The receive buffer holds 4 segments.At the start, it holds segments −2 and −1, acknowledged but not read.The sender window changes only when an advertisement arrives.

Event at the receiverReceive bufferReceiver sendsSender window
start−2, −1A = −1, window 20–1
reads −2−1nothing0–1
S = 0 arrives−1, 0A = 0, window 21–2
reads −1 and 0emptyA = 0, window 41–4
S = 1, S = 2 arrive1, 2nothing1–4
reads 1 and 2emptyA = 2, window 43–6
S = 3, S = 4 arrive3, 4A = 4, window 25–6
S = 5, S = 6 arrive3, 4, 5, 6A = 6, window 0none
reads 3 to 6emptyA = 6, window 47–10
S = 7 arrives7nothing7–10

A read frees buffer space, but the sender learns of it only from the next advertisement.If that advertisement is lost, the sender does not see the free space, so the transfer can stall.

Reading a TCP Exchange

A TCP connection is bidirectional: both hosts send and receive.Each direction has its own sequence numbers and its own window.Every segment carries the sequence number of its own data and the acknowledgement number for the other direction.

Piggybacking. With piggybacking, a data segment is also an ACK.Acknowledgements then need no separate packets.

Example 10. A full exchange.

Each line gives the data of a segment as first:last(length), then its acknowledgement number, SACK blocks and advertised window.The length is last−first+1\text{last} - \text{first} + 1, and (0) marks a segment without data.The numbers here are rounded for simplicity.Real sequence numbers lie between 0 and 232−12^{32}-1.

line  from  data              ack    sack          win
   1  A     8001:8500(500)    101                 6000
   2  B     101:200(100)      8501                4000
   3  A     8501:9000(500)    201                14247  lost
   4  A     9001:9500(500)    201                14247
   5  A     9501:10000(500)   201                14247
   6  B     (0)               8501   9001:9501    3500
   7  B     201:250(50)       8501   9001:10001   3000
   8  A     8501:9000(500)    251                14247
   9  B     251:400(150)      10001               2500
  10  B     (0)               10001               4000
  11  A     10001:10500(500)  401                14247

Before line 2, the application at B reads all bytes up to 8500.Lines 4 and 5 arrive after the gap of line 3, so B stores them and reports them in SACK blocks.These unread bytes shrink the window of B to 3500, then 3000.

At line 8, A retransmits bytes 8501:9000 after a timeout.Bytes 8501:10000 become readable, but the application is not ready yet, so the window of B drops to 2500.Once the application reads them, the window grows back to 4000.At line 10, B sends an empty segment only to advertise this window.

Window Size and Throughput

Round-trip time (RTT). The RTT is the time from a segment to its ACK.

Example 11. The smallest window for full speed.

A channel from A to B has capacity CC bytes per second.It has no loss or reordering.Which window WW lets A send at capacity?

A sends a full window in time W/CW/C.If W/C≥RTTW/C \ge \mathrm{RTT}, the first ACK returns before A finishes its window.The window then never blocks A, so A sends at rate CC.Otherwise, A sends its window and waits for an ACK, so it sends WW bytes per round trip.

rate=min⁡(C,WRTT)soWmin⁡=C×RTT\text{rate} = \min\left(C, \frac{W}{\mathrm{RTT}}\right) \quad\text{so}\quad W_{\min} = C \times \mathrm{RTT}

Only C×RTTC \times \mathrm{RTT} is in bytes, so C/RTTC / \mathrm{RTT} and RTT/C\mathrm{RTT} / C are dimensionally impossible.

The window Wmin⁡W_{\min} is the bandwidth-delay product, with the RTT in place of 2D2D and bytes in place of bits.It counts the bytes in flight when A sends at capacity.

ABrate ABrate data segmentACKRTTRTTidle, waiting for an ACK
Time runs right. Each band is one data segment sent at capacity CC.

With C=10C = 10 MB/s, an RTT of 50 ms and a window of 100 kB:

Wmin⁡=(10 MB/s)×(0.050 s)=500 kBrate=100 kB0.050 s=2 MB/s\begin{aligned} W_{\min} &= (10\ \text{MB/s}) \times (0.050\ \text{s}) = 500\ \text{kB} \\ \text{rate} &= \frac{100\ \text{kB}}{0.050\ \text{s}} = 2\ \text{MB/s} \end{aligned}

The 100 kB window therefore uses one fifth of the capacity.

Head-of-Line Blocking

Head-of-line (HOL) blocking. HOL blocking delays all data after a loss.Until TCP repairs the loss, the application cannot read the later data, even the bytes that already arrived.HOL blocking is a side effect of the streaming service.

Example 12. When is HOL blocking an issue?

ApplicationIssue?Reason
HTTP/1, one connection
per object
noa loss delays only its own object
HTTP/2, one connection
per page
yesa loss delays the whole page
a sensor, one measurement
per millisecond
yesa loss delays all newer measurements;
the application would rather skip it,
so it should use UDP

Connection Phases

A TCP connection has three phases:connection setup, data transfer and connection release.

Three-way handshake. The three-way handshake opens a connection.It synchronizes the sequence numbers, advertises the MSS, and makes sure that buffers and windows start empty.

Its three segments are a SYN, a SYN ACK and an ACK.The client does an active open: it sends the SYN.The server does a passive open: it listens and waits for the SYN.Initial sequence numbers are random, or pseudorandom as in SYN cookies.

Clientactive openServerpassive opentimelistensyn_sentsyn_rcvdSYN, seq=xestablishedSYN ACK, seq=y, ack=x+1establishedACK, ack=y+1
The three-way handshake, with the hues of Example 4. Boxes: the state that each host enters.

SYN and FIN each consume one sequence number, so the answer to seq=x is ack=x+1.

The connection release can happen in several ways.

Graceful release. A graceful release closes both directions in turn.Each host sends a FIN, and the other host acknowledges it.

Clientactive closeServerapplication closetimefin_wait_1close_waitFIN, seq=ufin_wait_2ack=u+1time_waitlast_ackFIN, seq=vclosedack=v+1
A graceful release, with the same hues and boxes as the handshake.

Between its ACK and its own FIN, the server can still send data.

Connection termination and lost or duplicated segments during setup raise more subtle cases.Computer Networking: Principles, Protocols and Practice treats them in sections 4.3.1 and 4.3.2.

The TCP Segment Format

IP header (20 or 40 bytes + options), protocol = TCPsource portdestination portsequence numberacknowledgement numberhlenrsvdflagswindowchecksumurgent pointeroptions (SACK, MSS)paddingsegment data, at most MSS bytesTCP header,20 bytes+ optionsTCP segment= IP data32 bits
A TCP segment inside an IP packet, 32 bits per row. Dashed fields are optional.

The TCP header has 20 bytes plus options, and hlen gives its length.The window field carries the advertised window.The checksum is mandatory.The options carry SACK blocks and the MSS.

FlagMeaning
SYNconnection setup
FINthe sender has reached the end of its byte stream
ACKthe acknowledgement number is valid
RSTreset: its reception aborts the connection
PSHpush: the segment must be created and delivered immediately
URGthe urgent pointer is valid
AE, CWR, ECEexplicit congestion notification, for congestion control;
AE is AccECN

SDU (Service Data Unit). An SDU is a block of data from the layer above.

PDU (Protocol Data Unit). A PDU is a block that a layer sends to its peer.The PDU of TCP is the segment.

Without the push bit, TCP may pack several SDUs into one PDU, and several PDUs into one SDU.Telnet sets the push bit after every end of line.

The URG bit announces urgent data, and the urgent pointer locates it.The urgent data need not be in the segment.The receiving TCP must tell the application that urgent data exists.Otherwise, the segment gets no special treatment.

RFC 6093 (2011) tells applications not to use urgent data.Implementations disagree on what the pointer marks:the last urgent byte or the byte after it.Middleboxes also routinely clear it.

Choosing the MSS

During the handshake, each host may advertise its receive MSS in the MSS option of its SYN segment.This MSS is the largest payload that the host accepts in one segment.Let HH be the size of the IP and TCP headers together.

advertised MSS=receive MTU−H\text{advertised MSS} = \text{receive MTU} - H

If the peer advertises nothing, TCP assumes these defaults.

IPv4:576−20−20=536 bytesIPv6:1280−40−20=1220 bytes\begin{aligned} \text{IPv4:}\quad 576 - 20 - 20 &= 536 \text{ bytes} \\ \text{IPv6:}\quad 1280 - 40 - 20 &= 1220 \text{ bytes} \end{aligned}

Here 576 bytes is the traditional minimum reassembly size of IPv4, and 1280 bytes is the minimum MTU of IPv6.

Each host then computes its own send MSS from its local MTU and the MSS that the peer advertised, MSSpeer\text{MSS}_{\text{peer}}.After the handshake, PMTUD or PLPMTUD replaces the local MTU with the current estimate of the path MTU.

MSS=min⁡(local MTU−H, MSSpeer)at the handshakeMSS=min⁡(PMTU−H, MSSpeer)after it\begin{aligned} \text{MSS} &= \min(\text{local MTU} - H,\ \text{MSS}_{\text{peer}}) && \text{at the handshake} \\ \text{MSS} &= \min(\text{PMTU} - H,\ \text{MSS}_{\text{peer}}) && \text{after it} \end{aligned}

Example 13. The MSS follows the path MTU.

A has a local MTU of 1500 bytes, and B advertises an MSS of 1200 bytes.Both headers have 20 bytes, so H=40H = 40 bytes.The MSS of A is min⁡(1460,1200)=1200\min(1460, 1200) = 1200 bytes.If PMTUD later finds a path MTU of 1000 bytes, the MSS drops to min⁡(960,1200)=960\min(960, 1200) = 960 bytes.

Modern operating systems use TCP Segmentation Offloading (TSO).The network interface card (NIC) then cuts the segments in hardware.This lowers the CPU load of TCP.

TCP Sockets

A TCP connection needs a server that listens and a client that connects.

CallSideDoes
bind()serverassociates the local port, here 5003, with the socket
listen()serverdeclares the size of the buffer that stores incoming SYNs
accept()serverblocks until a SYN arrives for its port;
creates a new socket for the connection;
returns it once the connection is established
connect()clientassociates the IP address and port 5003 of server S
with the socket, and sends a SYN
send()bothsends a block of bytes to the other end
recv(n)bothblocks until data is ready;
returns at most nn bytes;
raises an exception if the other end has closed

The server must call bind(); the client need not.

Example 14. A TCP client and server.

The client sends a string, and the server displays it.

# server S
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind(("0.0.0.0", 5003))
s1.listen()
while True:
    conn, addr = s1.accept()
    print(conn.recv(4096).decode())
    conn.close()
 
# client
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((S, 5003))
s.send(b"Networks are great!")
s.close()
Clientsocket sServer Ssockets s1 and conntimes1.listen()conn = s1.accept()s.connect((S, 5003))1SYN2SYN ACKaccept() returns conn3ACKs.send()conn.recv()datas.close()conn.close()
Example 14, with the hues of Example 4. Circles: the times 1, 2 and 3.
  1. At time 1, the server receives the SYN and enters syn_rcvd.It stores the client's IP address and port, MSS and sequence number.
  2. At time 2, the client receives the SYN ACK and enters established.Its socket s can now send and receive.
  3. At time 3, the server receives the ACK and enters established.

A real server has many clients, so it creates a new socket for each connection.

Non-connected socket. A non-connected TCP socket receives SYNs.

Connected socket. A connected TCP socket carries one connection.

In Example 14, s1 is the non-connected socket, and conn is a connected socket.A realistic server serves each connected socket in its own thread, while another thread keeps listening.

4-tuple. A 4-tuple holds two IP addresses and two ports.They are the source and destination of one connection, so the 4-tuple identifies the connection.Connected sockets can therefore share a local address and port.

Example 15. The TCP sockets of a host.

All five sockets use port 32456.The IPv4 sockets use the address 128.178.151.84, and the IPv6 sockets use 2001:620:618:1a6:3:80b2:9754:1.

SocketVersionKindReceives
3IPv4non-connectedSYNs
4IPv4connecteddata of connection 1
5IPv4connecteddata of connection 2
6IPv6non-connectedSYNs
7IPv6connecteddata of connection 3

A SYN goes to the non-connected socket of its destination address.Data goes to socket 4 or 5 by the segment's remote address and port.Each connected socket has its own receive buffer.