TCP, UDP and the endpoint that receives your data

See what a chat app really gets from TCP and from UDP, then follow arriving segments and datagrams to the socket that receives them. Transport protocols · Computer networks.

A chat app on a phone writes three messages to its server, one after another: Dinner, Yes and Parking. The server reads from the connection three times and gets DinnerY, then esPar, then king. Every byte arrived, in order, yet no read matches a message. On the same server, TCP and UDP both use port 443. How does the host know which socket to use?

What each protocol hands the application

The Transmission Control Protocol (TCP) gives the application an ordered stream of bytes. The three writes are 6, 3 and 7 bytes, 16 in all. TCP may pack them into segments however it likes (it can merge small writes, and a segment holds at most the maximum segment size), and a successful read can return some available bytes up to the requested size. A read need not take all waiting bytes; it can also report EOF or an error. In this trace the first read returns 7 bytes, DinnerY. The next reads return esPar and king. The stream keeps the order of the bytes, not the edges of the writes.

The User Datagram Protocol (UDP) works the other way. For these ordinary UDP sends, each send produces a datagram. A receive takes one datagram; it returns Parking whole if the buffer is large enough. On Linux, an undersized receive buffer truncates a datagram and discards the rest; recvmsg can report truncation. In exchange, UDP does nothing to repair the path: a datagram can be lost, duplicated or reordered, and UDP does not itself report a missing datagram. In this example the network loses Yes and delivers Parking before Dinner. Both arrive whole, out of order, and nothing flags the gap. An application that needs reliable ordered messages must supply suitable ordering and recovery or use a transport that provides them.

TCP reads and UDP datagrams

Read the steps as text

  1. The sender has 3 records: Dinner, Yes and Parking. TCP stream: the records go in as bare bytes. UDP datagrams: each record travels as its own datagram.
  2. TCP stream: the sender sends Dinner, Yes and Parking with nothing between them, 16 bytes in all. UDP datagrams: the sender sends 3 datagrams, one per record, 16 bytes in all.
  3. TCP stream: a 7-byte chunk arrives and the read returns DinnerY, which ends in the middle of Yes. UDP datagrams: a datagram carrying Parking arrives and is read whole.
  4. TCP stream: a 5-byte chunk arrives and the read returns esPar, which ends in the middle of Parking. UDP datagrams: a datagram carrying Dinner arrives and is read whole.
  5. TCP stream: a 4-byte chunk arrives and the read returns king. UDP datagrams: the datagram carrying Yes is lost and never reaches the receiver.

UDP's header is 8 bytes: source port, destination port, length and checksum. The length counts header and data, so a datagram carrying Parking has length 8 + 7 = 15. The checksum is optional over IPv4 and normally required over IPv6, with narrow tunnel-specific exceptions. Skipping repair suits data that goes stale fast: an old position update is useless once a newer one exists, so resending it, and holding the newer ones behind it as TCP's ordering would, helps nobody.

TCP retries and restores order, but a lasting failure can end the connection. A successful send does not prove the receiving app processed it. UDP skips the handshake and retransmissions; application delay still depends on loss and any recovery the app adds. Encryption belongs to a separate layer.

Putting the message edges back

A byte stream needs the application to write the edges in. The usual rules are a length prefix, which writes each message's length before it (6Dinner3Yes7Parking, 19 bytes), or a delimiter, which ends each message with a marker such as a newline. The reader adds whatever arrives to a buffer and cuts out a message whenever a whole one is there; a partial message waits for the next read. A length prefix works for any content. A delimiter works only if the marker cannot appear inside a message, or is escaped when it does.

An order tracker sends Paid, Packed and Shipped: 17 bytes bare, 20 with a length before each. The reads end at arbitrary points in both runs, but only the prefixed reader can tell where a message ends. Each length here is one character, enough for messages up to 9 letters; real protocols may use a fixed-width or variable-width length field.

Putting the edges back with a length

Read the steps as text

  1. The sender has 3 records: Paid, Packed and Shipped. Raw: the records go in as bare bytes. Prefixed: each record is preceded by its length.
  2. Raw: the sender sends Paid, Packed and Shipped with nothing between them, 17 bytes in all. Prefixed: the sender sends Paid, Packed and Shipped with a length before each record, 20 bytes in all.
  3. Raw: a 6-byte chunk arrives and the read returns PaidPa, which ends in the middle of Packed. Prefixed: a 7-byte chunk arrives and the read returns [4]Paid[6]P; the parser extracts Paid, keeps the length and 1 body letter and needs 5 more.
  4. Raw: a 6-byte chunk arrives and the read returns ckedSh, which ends in the middle of Shipped. Prefixed: a 6-byte chunk arrives and the read returns acked[7]; the parser extracts Packed, keeps the length and needs 7 body letters.
  5. Raw: a 5-byte chunk arrives and the read returns ipped. Prefixed: a 7-byte chunk arrives and the read returns Shipped; the parser extracts Shipped.

Which socket gets an arriving segment

The IP address brings a packet to the right machine. The machine must then pick a socket, the endpoint a program holds open. An established TCP connection is named by four values, its four-tuple: local IP address, local port, remote IP address and remote port. A server at 10.4.0.20 listens on TCP port 443, and two phones, 10.4.0.31 and 10.4.0.32, connect to it.

Each phone's system picks its own ephemeral (short-lived) source port, from a system-configured ephemeral range, so both can pick 51000; the sockets lesson covers where that port comes from. The connections are (10.4.0.20, 443, 10.4.0.31, 51000) and (10.4.0.20, 443, 10.4.0.32, 51000). The tuples differ, so these are two connections, told apart by the remote address.

For the ordinary IPv4 arrivals in this example, with valid checksums and no filtering, the host uses this simplified lookup. First, an established connection with exactly that four-tuple, which gets the segment. Otherwise, if the segment is a SYN (the opening step of a new connection), a listening socket on the destination port whose address is the destination address or 0.0.0.0, which starts a new connection. A socket bound to the specific address beats one bound to 0.0.0.0. For the unmatched non-RST unicast segment in this example, the host answers with a reset (RST). TCP does not answer an incoming RST with another reset.

UDP is connectionless at the transport level; a UDP socket can nevertheless be connected to a peer for local filtering and a default destination. In this example the sockets are unconnected, and the host matches the datagram's destination address and port to their local bindings; the address 0.0.0.0 matches every address of the host, and in this modeled Linux setup an allowed specific binding beats the wildcard.

TCP and UDP keep separate tables, so TCP port 443 and UDP port 443 are different endpoints. In the example, a datagram for UDP port 443 goes to the QUIC server (QUIC is a transport over UDP), bound to 10.4.0.20, not to a metrics agent on 0.0.0.0. If no UDP socket matches, the datagram is dropped; an ICMP port-unreachable may be sent, subject to filtering and other conditions.

Which socket gets each arrival

Read the steps as text

  1. Server has the address 10.4.0.20 and 5 sockets: 3 TCP and 2 UDP. Each of the 4 packets that will arrive is looked up in the socket table.
  2. A TCP segment that is not a SYN reaches Server from 10.4.0.32 port 51000, addressed to 10.4.0.20 port 443.
  3. TCP and UDP use separate tables. The kernel first looks in the TCP table for an established connection with the four-tuple 10.4.0.32:51000 to 10.4.0.20:443. One row has exactly that tuple.
  4. Web server's socket on 10.4.0.20 port 443 takes it. Its row has exactly this four-tuple.
  5. The segment goes to Web server through that connection. Its received count is now 1.
  6. A UDP datagram reaches Server from 10.4.0.32 port 51000, addressed to 10.4.0.20 port 443.
  7. The kernel looks in the UDP table for a socket bound to 10.4.0.20 or 0.0.0.0, which means every local address on port 443. Two rows qualify.
  8. QUIC server's socket on 10.4.0.20 port 443 wins. It is bound to 10.4.0.20, and a socket bound to the host address beats the wildcard 0.0.0.0.
  9. The datagram goes to QUIC server through that socket. Its received count is now 1.
  10. A TCP SYN segment reaches Server from 10.4.0.33 port 51000, addressed to 10.4.0.20 port 443.
  11. The kernel first looks in the TCP table for an established connection with the four-tuple 10.4.0.33:51000 to 10.4.0.20:443. No row has that tuple.
  12. The segment is a SYN, so the kernel next looks for a listening socket for port 443 at 10.4.0.20 or at 0.0.0.0. One row qualifies.
  13. Web server's socket on 0.0.0.0 port 443 takes it. It is bound to 0.0.0.0.
  14. The kernel completes the handshake and adds an ESTABLISHED row for 10.4.0.33:51000 to 10.4.0.20:443. The new row belongs to Web server, the process that owns the listener, and the listener row stays.
  15. A TCP segment that is not a SYN reaches Server from 10.4.0.34 port 51000, addressed to 10.4.0.20 port 443.
  16. The kernel first looks in the TCP table for an established connection with the four-tuple 10.4.0.34:51000 to 10.4.0.20:443. No row has that tuple.
  17. A segment that is not a SYN needs an established connection, and no row has this tuple, so the host answers with a reset (RST).

These examples simplify in four ways: each host has one IPv4 address; this is a Linux-style unicast lookup without SO_REUSEPORT; the unconnected UDP sockets use permitted SO_REUSEADDR bindings; and byte counts exclude headers. How a listener hands a finished connection to the program with accept is the subject of a later lesson on sockets and ports.

Recap

  • TCP gives an ordered byte stream, so the chat reads came back as 7, 5 and 4 bytes; the application adds a length or a delimiter to find its messages again.
  • UDP preserves datagram boundaries, subject to receive-buffer truncation, but does not repair loss or reordering.
  • In this setup the host demultiplexes by protocol and then by four-tuple (TCP) or unconnected local binding (UDP), so two clients with the same source port, and TCP and UDP on one port number, reach different sockets.