every-protocol-is-bytes-on-a-socket.md

← Writing Desktop 17 min read

Every protocol is just bytes on a socket

HTTP, Redis and SMTP look nothing alike, but they all do the same thing underneath. How they work, and how to design a small protocol of your own.

Created
Aug 30, 2026
Reading
17 min
Labels
networkingbackend

HTTP, Redis, SMTP and SSH look nothing alike. Underneath, they all do the same job: one program writes bytes to a socket, and another program reads them.

The socket has no idea what those bytes mean. A protocol is the two sides agreeing on what they mean.

This post starts with an ordinary HTTP request and works down to the socket, then builds a small protocol from scratch. Everything below ran in a Debian container, so you can repeat it.

Start at the top

Ask curl to show you what it sends and receives:

$ curl -sv http://example.com -o /dev/null 2>&1 | grep -E '^[<>]'
> GET / HTTP/1.1
> Host: example.com
> User-Agent: curl/8.14.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Server: cloudflare

Lines starting with > are what curl sent, and lines starting with < came back. It is just text: a request line, a few headers, and a blank line to say the headers are over. The server answers in the same shape. I cut some headers to save space.

Do it by hand

If HTTP is only text, you should be able to type it yourself. nc (netcat) opens a connection and lets you send whatever you want:

$ printf 'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n' | nc example.com 80
HTTP/1.1 200 OK
Date: Mon, 30 Nov 2026 07:18:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Server: cloudflare
...

A real web server answered a request I typed myself, with no browser or library involved. The request was a GET, a path, a Host header and a blank line.

Lines end with \r\n, not just \n, because that is what the HTTP spec says. I also added Connection: close so the server hangs up when it is done, otherwise nc keeps waiting.

Port 80 is plain HTTP, so anyone on the path can read it. Real sites use HTTPS on port 443, which wraps the same text in encryption. I use port 80 here only so the bytes are readable.

What a socket is

That worked because HTTP is only the top layer. Your program does not talk to the network directly. It asks the operating system for a socket, which comes back as a file descriptor, the same kind of number you get when you open a file. Then it uses connect, write and read on it.

HTTP, Redis, SMTP: text or bytes you define TLS: optional encryption (the S in HTTPS) TCP or UDP: how bytes get between programs IP: packets between machines your program talks througha socket
The layers. Your program gets a socket, and everything above TCP or UDP is an agreement about what the bytes mean.

If you read my strace post, you already have the tool to watch this. Here is curl fetching that page:

$ strace -f -e trace=socket,connect curl -s http://example.com -o /dev/null
socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, IPPROTO_IP) = 5
connect(5, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("...")}, 16) = 0
socket(AF_INET6, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_IP) = 5
connect(5, {sa_family=AF_INET6, sin6_port=htons(80), ..., "2606:4700:10::ac42:93f3", ...}, 28) = -1 ENETUNREACH (Network is unreachable)
connect(5, {sa_family=AF_INET, sin_port=htons(80), sin_addr=inet_addr("172.66.147.243")}, 16) = 0

I trimmed the output and hid the DNS server’s address. The first two lines are curl asking DNS where example.com lives, over a UDP socket to port 53. Then it tries an IPv6 address on port 80, which the container could not reach, and finally connects over IPv4 (= 0 means connected).

After that, curl writes the request text to the socket and reads the answer back.

The same thing in ten lines

Any language with sockets can do what curl does. Here is a page fetcher with no libraries:

import socket

s = socket.create_connection(("example.com", 80))
s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")

data = b""
while chunk := s.recv(4096):
    data += chunk

head, _, body = data.partition(b"\r\n\r\n")
print(head.decode())
print("...body is", len(body), "bytes")
$ python3 fetch.py
HTTP/1.1 200 OK
Date: Mon, 30 Nov 2026 07:18:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
...
alt-svc: h3=":443"; ma=86400
...body is 589 bytes

The loop reads until recv returns nothing, which means the other side closed the connection. The body count includes some chunk markers, because I did not decode Transfer-Encoding: chunked. A real client would.

Keep an eye on the alt-svc header. It says this site also speaks HTTP/3, and we will get to why that matters.

TCP and UDP

When you create a socket you choose a transport, and the two common choices behave very differently.

TCP SET city kathmandu\nGET city\n a connection, bytes arrive in order, lost ones are sent again. but there are no message boundaries. UDP packet 1 packet 2 packet 3 no connection, each packet stands alone, it can arrive late, twice, or never. but each one keeps its own boundary. Used for: web, databases, email, SSH. Used for: DNS, calls, games, HTTP/3.
TCP gives you a reliable stream. UDP gives you separate packets and no promises.

TCP sets up a connection first, so both sides know they are talking. After that, bytes arrive in order, lost ones are sent again, and the sender slows down if the receiver cannot keep up. Web pages, databases and email use it for that reason. What it does not keep is your message boundaries: it is a stream of bytes, with nothing marking where one message ends.

UDP makes no promises. There is no connection, and packets can be lost, duplicated or reordered. In exchange it is light and fast, and each packet arrives as its own message. DNS uses it, because a lookup is one small question and one small answer.

You saw that in the strace output earlier: curl made a SOCK_DGRAM socket and talked to port 53 before it ever opened the TCP connection to port 80.

Here is a UDP server that answers every packet it gets:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("127.0.0.1", 9001))
while True:
    data, addr = s.recvfrom(1024)
    s.sendto(b"echo: " + data, addr)
$ echo hello | nc -u -w1 127.0.0.1 9001
echo: hello

Notice there is no accept and no connect. The server just receives a packet and replies to whoever sent it.

That alt-svc: h3 header is the other place UDP shows up. HTTP/3 runs over UDP using a protocol called QUIC, which rebuilds the reliability TCP gave you in a way that is easier to change.

Other protocols are the same kind of agreement

SMTP (email) is also text, one command per line, and the server answers each line with a numbered status. In principle you could send mail with nc the way we fetched a page, though many servers block it.

Redis looks like this on the wire:

*2\r\n$3\r\nGET\r\n$3\r\nfoo\r\n

That is the command GET foo. *2 says “an array of two items”, and each $3 says “a string of three bytes follows”. Redis sends the length before the data, so the reader always knows how much to read. Redis even accepts plain GET foo typed by hand, which is why it is so easy to debug.

Postgres and SSH are binary, not text. A Postgres message is a type byte followed by a four-byte length and then the payload. You cannot type that into nc, but it is the same idea: agreed bytes on a socket.

They differ in a few choices: text or binary, TCP or UDP, a length up front or a delimiter at the end. Those are the same choices you make when you write your own, which is what we do next.

Design your own

Say you want a tiny key-value store, where SET name samir stores a value and GET name reads it back. You need to decide five things.

  1. Framing. TCP gives you a stream, not messages. How does the reader know where one message ends? Either mark the end (HTTP headers end at a blank line, Redis commands at \r\n) or send the length first.
  2. Shape. What does a request look like, and what does a reply look like? Who speaks first?
  3. Errors. How does a failure look different from a normal answer?
  4. Text or binary. Text is easy to read and debug. Binary is smaller and faster.
  5. Change. How will you add a new command later without breaking old clients? A version number, or only ever adding commands, are the usual answers.

I will pick the simplest choice for each: text, one command per line, a newline ends a message, and replies are one line too (OK, a value, (nil), or ERR ...). Here is a server for it:

import socket

store = {}
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen()

def handle(line):
    parts = line.split(" ", 2)
    cmd = parts[0].upper()
    if cmd == "SET" and len(parts) == 3:
        store[parts[1]] = parts[2]
        return "OK"
    if cmd == "GET" and len(parts) == 2:
        return store.get(parts[1], "(nil)")
    return "ERR bad command"

while True:
    conn, _ = srv.accept()
    buf = b""
    while data := conn.recv(1024):
        buf += data
        while b"\n" in buf:                 # a message ends at a newline
            line, buf = buf.split(b"\n", 1)
            conn.sendall((handle(line.decode().strip()) + "\n").encode())
    conn.close()

You can talk to it with the same nc as before:

$ printf 'SET name samir\nGET name\nGET nothing\nHELLO\n' | nc -q1 127.0.0.1 9000
OK
samir
(nil)
ERR bad command

That is a working protocol. The server listens on 127.0.0.1, so only your own machine can reach it. Keep it that way while you experiment.

The -q1 flag is for the OpenBSD netcat that Debian ships. The nc on macOS and other systems takes different flags, so check man nc if it hangs.

The bug that teaches framing

The server works with one command at a time. What if a client sends two in one go?

import socket, time
s = socket.create_connection(("127.0.0.1", 9000))
s.sendall(b"SET city kathmandu\nGET city\n")   # two commands, one send
time.sleep(0.3)
print(repr(s.recv(1024)))

Against the server above, this works:

$ python3 twomsg.py
b'OK\nkathmandu\n'

Now try it against the lazy version of the server, which assumes that one recv call is one command:

while data := conn.recv(1024):
    parts = data.decode().strip().split(" ", 2)   # assumes one recv() == one command
$ python3 twomsg.py
b'OK\n'

One reply instead of two. The first recv returned both commands glued together, and the code split the text as if it were a single command. Everything after the first space was treated as the value, so the stored value is kathmandu\nGET city, and the second command was swallowed.

the sender wrote SET city kathmandu\n GET city\n recv() might return SET city kathmandu\nGET city\n both at once SET city k athmandu\nGET city\n cut in the middle
TCP does not remember where your messages started and stopped. It only promises the bytes come out in the same order.

The reverse also happens. A message can arrive in two pieces, so the first recv returns half a command. This depends on timing and the network, which is why this bug often works on your laptop and breaks in production.

The fix is what the good server does: keep a buffer, add every recv to it, and only act on complete messages. In our protocol a message is complete when you see a \n. Anything left over stays in the buffer for the next read.

Length prefix: the other way to frame

A newline stops working as the end marker if a value can contain a newline. The other common answer, used by Redis and Postgres, is to say how long the message is before you send it.

import struct

def pack(msg: bytes) -> bytes:
    return struct.pack(">I", len(msg)) + msg      # 4-byte length, then the payload

def unpack(buf: bytes):
    msgs = []
    while len(buf) >= 4:
        (n,) = struct.unpack(">I", buf[:4])
        if len(buf) < 4 + n:
            break                                  # message not complete yet
        msgs.append(buf[4:4 + n])
        buf = buf[4 + n:]
    return msgs, buf
$ python3 lp.py
b'\x00\x00\x00\x12SET city kathmandu\x00\x00\x00\x08GET city'
([], b'\x00\x00\x00\x12SET ci')
([b'SET city kathmandu', b'GET city'], b'')

The first line is the bytes on the wire: a length (\x12 is 18), the message, then another length (\x08) and the next message. The second line is a half-arrived buffer, and unpack correctly returns nothing and keeps the partial bytes. The third is the full buffer, which splits into the two original messages.

The values can contain anything now, including newlines, because the reader never has to look for an end marker. The cost is that you can no longer type it into nc by hand.

Where to go next

TCP does not keep your message boundaries, so any code that reads from a TCP socket needs a buffer and a framing rule. Skipping that is behind a lot of bugs that only show up on a real network.

Text protocols are easier to debug, because you can type a request into nc or watch it in curl -v. I would choose binary only when size or speed matters.

Not every protocol runs on a network socket. Programs on one machine also talk through pipes and shared memory. Between two machines, though, there is a socket in the middle.

To keep going, run strace on a command-line tool you use and look for socket and connect.

The examples above ran against example.com and a local Python 3 server in a Debian container with curl 8.14.1.

← All writing Share on LinkedIn RSS