Sub topic 5
Starting point: application data
Every trip across a network begins with application data. This is the content a program wants to send, before any transport, network or link header exists. This chapter covers what that data is and how it becomes bytes. It also covers what the layer below does with it and the mistakes that follow from misunderstanding it. It assumes you know what a header and a payload are, and that you can read hexadecimal and run Python and shell commands.
What counts as application data
Application data is the byte sequence that a program passes to the transport layer through the operating system. The transport layer treats these bytes as an opaque payload. It does not parse them or care what they mean.
The application defines the meaning. An HTTP client, a DNS resolver, an SSH session and a game client each produce different bytes. Each follows its own application protocol, which is a set of rules for message structure, ordering and encoding.
| Application protocol | Typical transport | Example of application data |
|---|---|---|
| HTTP/1.1 | TCP, port 80 | A request line, header lines and an optional body, all as text |
| DNS | UDP, port 53 | A binary message with a question such as "A record for example.com" |
| TLS | TCP, port 443 | Encrypted records that contain the HTTP data |
| SSH | TCP, port 22 | Encrypted binary packets |
An application protocol has headers of its own. An HTTP Host: line is a header, and so is the fixed 12-byte header at the start of a DNS message. These belong to the application and are part of the data from the point of view of every lower layer. When this tutorial says "header" without qualification, it means the headers added by TCP, UDP, IP and Ethernet.
From program objects to bytes
A network carries only bytes. Before sending, the program must serialize its data, meaning it converts values in memory into a defined byte layout. Both ends must agree on that layout.
Text protocols such as HTTP/1.1 use human-readable characters. They need an agreed character encoding and agreed line endings. HTTP uses \r\n (carriage return plus line feed, bytes 0x0D 0x0A) to end each line. A blank line (\r\n\r\n) ends the header section.
Binary protocols such as DNS pack numbers into fixed fields. They use network byte order, which is big-endian: the most significant byte comes first. The Python "!" prefix in struct selects this order, and the Python example in the encapsulation chapters uses it for the same reason.
A short HTTP request shows the difference between characters and bytes:
request = (
"GET / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n"
).encode("ascii")
print(len(request))
print(request[:14])
print(request[:14].hex(" "))This prints 56, then b'GET / HTTP/1.1', then 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31. The 56 bytes are all the application contributes. Every header added by lower layers sits on top of them.
Characters are not bytes
In UTF-8, a character can take one to four bytes. The word café is four characters but five bytes, because é takes two. Protocol fields that carry a length, such as HTTP Content-Length, count bytes. If you compute the length with len(text) instead of len(text.encode("utf-8")), the receiver waits for bytes that never arrive or cuts the message short.
How a program hands data to the network
A program does not build TCP segments. It opens a socket, an operating system object that represents one endpoint of a conversation. It then writes bytes into the socket. The operating system's network stack takes over from there.
import socket
request = (
"GET / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n"
).encode("ascii")
with socket.create_connection(("example.com", 80), timeout=5) as s:
s.sendall(request)
chunks = []
while True:
chunk = s.recv(4096)
if not chunk:
break
chunks.append(chunk)
response = b"".join(chunks)
head, _, body = response.partition(b"\r\n\r\n")
print(head.decode("iso-8859-1").splitlines()[0])
print(len(body), "bytes of body")create_connection resolves the name, performs the TCP handshake and returns a connected socket. sendall passes the 56 request bytes to the kernel. The loop reads until recv returns an empty bytes object, which signals that the server closed the connection. We asked for that with Connection: close.
Nothing in this program mentions ports in headers, IP addresses in headers or MAC addresses. The code supplies a destination host and port. The kernel fills in every header field.
Byte streams and message boundaries
The transport protocol changes what the application sees, so the choice of TCP or UDP affects how you write the application.
- TCP gives the application a byte stream. It does not preserve the boundaries of your
sendcalls. Two sends of 6 bytes might arrive as one read of 12 bytes, or as reads of 5 and 7 bytes. - UDP preserves boundaries. One
sendtocall produces one datagram, and onerecvfromcall returns exactly one datagram. The datagram may be lost, duplicated or reordered, though.
The next program shows the TCP behavior on the loopback interface. The server makes two separate sends, and the client prints each chunk it receives.
import socket
import threading
def serve(listener):
conn, _ = listener.accept()
with conn:
conn.sendall(b"first,")
conn.sendall(b"second")
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(1)
threading.Thread(target=serve, args=(listener,), daemon=True).start()
client = socket.create_connection(listener.getsockname())
data = b""
while True:
chunk = client.recv(1024)
if not chunk:
break
print("chunk:", chunk)
data += chunk
client.close()
listener.close()
print("total:", data)The total line is always b'first,second'. The chunk lines vary between runs: you may see one chunk or two. Because of this, a TCP application protocol must mark where each message ends. The common techniques are:
- A length prefix, where each message starts with its byte count. DNS over TCP and TLS records do this.
- A delimiter, such as the blank line that ends HTTP headers.
- A close of the connection, as in the
Connection: closeexample above.
What the transport layer does with the data
Once the bytes sit in the socket's send buffer, the kernel takes over. For TCP, it cuts the stream into pieces no larger than the maximum segment size (MSS). It puts each piece behind a TCP header, as the next chapters show. For UDP, it adds a UDP header to each datagram as a whole. A UDP datagram larger than the path allows is fragmented at the IP layer, or the send fails. This is why UDP applications such as DNS keep messages small.
So the size of your application data does not equal the size of anything on the wire. The 56-byte request fits in one segment. A 1 MB upload becomes hundreds of segments. A one-byte write may be delayed and merged with later writes, because TCP's Nagle algorithm batches small writes unless the program disables it with the TCP_NODELAY option.
When TLS is involved
With HTTPS, the application data is not the plaintext HTTP request that reaches the transport layer. The TLS library encrypts it first and wraps it in TLS records. The transport layer then treats the encrypted record as the payload.
This matters when you inspect traffic. Your capture can show the Ethernet, IP and TCP headers for any connection. You can read the application payload only if the protocol is unencrypted or you hold the session keys.
Common errors
- Assuming one
sendequals onerecvon TCP. This works on a fast local network, then breaks under load or on a slower link. Always frame your messages. - Using
sendinstead ofsendall.sendmay write only part of the buffer and returns the count it wrote.sendallloops until everything is queued. - Forgetting
\r\n. An HTTP request ending in\n\nis not a well-formed request, and many servers hang waiting for the blank line or reject it. - Omitting the
Hostheader in HTTP/1.1. The request is invalid, and servers that host many sites cannot tell which one you want. - Measuring length in characters. Use the encoded byte count.
- Treating
recv(n)as "read exactly n bytes". It returns up tonbytes. Loop until you have what you need. - Reading until the socket closes when the server keeps it open. With HTTP keep-alive, the loop in the first example blocks until the timeout unless you send
Connection: closeor parseContent-Length.
Exercise
A client encodes the string "naïve café" with UTF-8 and sends it over TCP as the body of an HTTP request. It sets Content-Length: 10, the number of characters. The server stalls or returns an error. What is wrong, what value is correct, and why might the server receive the body in two separate reads even though the client called sendall once?
Show answer
Content-Length counts bytes, not characters. In UTF-8, ï and é each take two bytes, so "naïve café" is 10 characters but 12 bytes. The correct value is 12. With 10, the server reads a truncated body and treats the last 2 bytes as the start of the next message, or it reports an error. The server may see two reads because TCP is a byte stream. The kernel may split the data into several segments, or the receiver may read before all segments have arrived. The boundaries of the client's sendall call are not preserved.