Sub topic 3
Connectionless versus connection-oriented delivery
This chapter assumes you know the four-layer model (application, transport, network, link). It also assumes you know that IP moves packets between hosts on a best-effort basis, and that you can read short Python programs. Ports and sockets were covered in the previous chapter. Here the question is how two endpoints relate to each other before, during, and after they exchange data.
Two models of delivery
IP gives the transport layer one service: try to deliver this packet to that address. It does not promise delivery, ordering, or absence of duplicates. Transport protocols build on that foundation in one of two ways.
- Connectionless delivery treats every message as independent. The sender addresses a message and sends it. No setup happens first, and neither side remembers the exchange afterward. UDP works this way.
- Connection-oriented delivery has the two endpoints agree to talk before any application data moves. Both sides then keep shared state for the life of the conversation. TCP works this way.
A common analogy is a postcard versus a phone call. It helps with the setup step, but it can mislead. A TCP "connection" is not a reserved circuit. Routers in the middle know nothing about it, and every TCP segment still travels as an ordinary best-effort IP packet. The connection exists only as state held in the two end hosts.
What "connection" means
A TCP connection is a set of variables kept by each endpoint. Typical contents:
- The connection's identity: local and remote IP address and port.
- Sequence number counters for data sent and received.
- A record of which bytes have been acknowledged.
- Buffers holding data not yet sent, not yet acknowledged, or not yet read by the application.
- Window sizes and timers that control how fast to send.
- The current state in the TCP state machine, such as established or closing.
The setup exchange exists to initialize this state consistently on both sides. A later chapter covers the three-way handshake itself. What matters here is the consequence: once both sides hold this state, each can detect loss, reorder data, and slow down. A connectionless protocol has no such state, so it cannot do those things.
A UDP socket keeps almost nothing about the peer. It has a local address and port, and a queue of arrived datagrams. Each call to sendto names its destination, and each datagram from recvfrom reports its source.
A side-by-side view
The diagram below shows the shape of each exchange. In the connectionless case, messages stand alone. In the connection-oriented case, setup comes first and teardown comes last.
Guarantees compared
The guarantees differ because the state differs.
| Property | Connectionless (UDP) | Connection-oriented (TCP) |
|---|---|---|
| Setup before data | None | Yes, one round trip before the first data byte |
| State kept per peer | Almost none | Sequence numbers, windows, timers, buffers |
| Delivery | Best effort, loss is silent | Retransmits until acknowledged or the connection fails |
| Ordering | Not guaranteed | Bytes delivered in the order sent |
| Duplicates | Possible | Removed by the receiver |
| Unit of data | Message (datagram) with boundaries | Byte stream without boundaries |
| Pacing | Sender sends as fast as it likes | Flow control and congestion control limit the rate |
| Failure reported to the application | Rarely | Yes, as an error or a closed connection |
The last row deserves attention. TCP does not promise that data always arrives. It promises that data arrives correctly and in order, or that you find out it did not. If the network is cut for long enough, TCP gives up and the socket reports an error.
Seeing the difference in code
The clearest behavioral difference appears when nobody is listening. The program below sends to a port where, we assume, no process is bound. It uses port 54321 on the local machine. Change the number if something is using it.
import socket
PORT = 54321 # assumed unused on this machine
# Connectionless: the send "succeeds" even though nobody is there.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as u:
sent = u.sendto(b"anyone home?", ("127.0.0.1", PORT))
print("UDP sendto returned", sent)
# Connection-oriented: connect() fails because setup cannot complete.
try:
with socket.create_connection(("127.0.0.1", PORT), timeout=2):
print("TCP connected")
except ConnectionRefusedError:
print("TCP connect refused: no listener on that port")Expected output on a typical Linux or macOS machine:
UDP sendto returned 12
TCP connect refused: no listener on that portThe UDP call returns 12, the number of bytes handed to the operating system. That number says nothing about whether anyone received them. The TCP call fails at once, because the setup request got a refusal in reply. The failure is useful: the application learns the peer is absent before it sends anything.
On some systems, a UDP socket can later receive an ICMP "port unreachable" message and report it as an error on a subsequent call. Linux reports it on unconnected sockets only in limited cases, and Windows reports it as ConnectionResetError from recvfrom. Code that must run on several platforms should not rely on this behavior.
Costs of each model
Setup latency
A connection costs at least one round trip before the first byte of application data can be sent. On a path with a 100 ms round trip, that is 100 ms added to every new connection. Encryption layers on top of TCP, such as TLS, add further round trips. A UDP message can go out at once. This matters most for short exchanges. A single DNS lookup is one small request and one small reply, and a connection setup would double or triple the round trips for it.
Per-peer memory and server scaling
A TCP server holds state for every open connection. With tens of thousands of clients, memory and tracking costs become a design concern. A UDP server using one socket can serve any number of clients, because each datagram carries its own source address and the server remembers nothing unless the application chooses to.
The same state creates an attack surface. A flood of connection-setup requests can fill the table of half-open connections. Operating systems defend against this with techniques such as SYN cookies, which let the server avoid storing state until the client proves it is real. A connectionless server has a related problem: it will answer anyone, so attackers can spoof source addresses and use it to flood a victim.
Failure detection
With a connection, both sides hold state that can expire. If a peer crashes or a cable is cut, TCP's retransmission timers eventually fire and the application gets an error. There is a caveat. A TCP connection with no traffic can sit silently for hours after the network path dies, because nothing is being sent to notice the failure. Applications that need quick detection add heartbeats or enable TCP keepalive.
With connectionless delivery, the transport never notices anything. The application must supply its own timeouts, as the UDP example in this tutorial's code section does with settimeout.
Message framing
A connectionless datagram arrives as one unit, with the size the sender used. A TCP stream does not preserve write boundaries. Two sendall calls may arrive as one read, or one call may arrive in several reads. Applications on TCP must add their own framing, such as a length prefix or a delimiter. A later chapter covers this in detail.
Building on top of the other model
The two models are not rigid. You can add features to one to approximate the other.
- Reliability over UDP. Applications add sequence numbers, acknowledgments, and retransmission themselves. QUIC does this and also adds encryption and multiple streams, and it runs over UDP. Doing this in the application allows changes without waiting for operating system updates and avoids some TCP delays, but it means rebuilding hard machinery correctly.
- Message semantics over TCP. Framing layers such as length-prefixed records turn the stream back into messages. Many protocols, such as HTTP/1.1, define how to find message ends.
- "Connected" UDP sockets. Calling
connect()on a UDP socket does not send anything. It only records the default peer, so you can usesendinstead ofsendto, and the kernel drops datagrams from other sources. The delivery model is still connectionless.
Common mistakes
- Assuming a successful UDP send means delivery. The return value counts bytes accepted by the local operating system, not bytes received.
- Assuming one TCP
sendequals onerecv. TCP delivers a stream. Always loop and frame your messages. - Assuming a quiet TCP connection is a healthy one. Without traffic or keepalive, a dead path can go unnoticed for a long time.
- Waiting forever on UDP. Without a timeout, a lost datagram blocks
recvfromindefinitely. - Treating a connection as a network resource. Routers do not track TCP connections, though firewalls and NAT devices often do, and they may drop idle ones.
Summary of the decision at this level
Pick the connection-oriented model when the application needs every byte, in order, and can accept setup latency and per-connection state. Pick the connectionless model when messages are small and independent, when timeliness matters more than completeness, or when the application wants to control loss recovery itself. The final chapter of this tutorial applies these criteria to concrete applications.
Exercise
A client sends one request and expects one reply. Over a 80 ms round-trip path, how long does it take, at minimum, to get the reply using (a) UDP and (b) a fresh TCP connection, ignoring processing time and any encryption? Which round trips make up the difference?
Show answer
(a) UDP needs one round trip: the request goes out immediately and the reply comes back, about 80 ms. (b) A fresh TCP connection needs one round trip for connection setup before the request can be sent, then one round trip for the request and reply, about 160 ms in total. The extra 80 ms is the setup exchange. (In practice the client can send its request along with its final setup message, but the server's reply still arrives only after the setup round trip plus the request round trip.)
Exercise
A program calls sendto on a UDP socket and it returns the number of bytes in the message. The server was never started. Why does the call not fail, and what must the application do to find out the message was not delivered?
Show answer
sendto only hands the datagram to the local operating system, which sends it as an IP packet. No setup occurred, so nothing told the sender the peer is absent. The application must detect it itself, typically by waiting for a reply with a timeout (settimeout followed by recvfrom) and retrying or giving up when the timeout expires.
Exercise
Why can a single UDP socket serve thousands of clients with almost no per-client memory, while a TCP server needs state for each client?
Show answer
A UDP datagram carries its own source address and is handled independently, so the server needs no record of past exchanges unless the application keeps one. TCP guarantees reliable ordered delivery, which requires per-connection state: sequence numbers, acknowledgment tracking, buffers, window sizes, and timers.