The Complete Guide to Writing Network Protocol Parsers and Stacks
Build network protocol parsers and a small TCP/IP stack in C: framing, bounds-safe parsing, state machines, packet buffers, testing, fuzzing and limits.

Every network program is, underneath, a parser with a state machine attached. Bytes arrive from an untrusted peer, in whatever chunks the network felt like delivering, and the program must turn them into decisions without crashing, without being tricked, and without losing its place when a message is split across reads. A protocol stack is the same problem repeated at every layer: Ethernet frames contain IP packets, which contain TCP segments, which contain application messages, and each layer parses, validates and hands on. This guide teaches the whole craft in C on Linux 6.12 with GCC 14 and glibc 2.40: how to structure a parser so it is safe by construction, how to handle framing and partial input, how to decode real formats such as DNS and IPv4, how to write the state machines that give stateful protocols their behaviour, how to build the packet buffers and layers of a small stack, and how to test and fuzz all of it. It assumes you can write C and read a hex dump. Each section builds on the last, with code you can compile and output worked out by hand, so you can check your own understanding against it.
The shape of every protocol implementation
Before any code, fix the architecture in your head, because nearly every bug in a network program comes from blurring one of its layers into another. A protocol implementation has five jobs, and they should live in separate pieces of code.
The first is I/O: getting bytes from a socket, a device or a file, and sending them back. The second is framing: deciding where one message ends and the next begins in a stream of bytes. The third is parsing: turning the bytes of one framed message into typed fields, with every length and offset checked. The fourth is validation: deciding whether the parsed message is acceptable, given the protocol rules and the current state. The fifth is the state machine: deciding what to do next, which may mean sending a reply, changing state, starting a timer or closing the connection.
The discipline is that data flows in one direction through these pieces and each does only its own job. The parser never reads from a socket. The I/O code never interprets a field. The state machine never touches raw bytes; it receives events built from parsed, validated messages. When these are separate, each can be tested alone: you can feed the parser a byte array with no network, and you can drive the state machine with a script of events. When they are tangled, you can only test the whole program against a live peer, and the bugs hide in the interactions.
A second principle runs through the guide: treat all input as hostile and all lengths as lies. A length field in a packet is a claim made by the sender, and a parser that believes it, to size an allocation or bound a loop or compute an offset, hands control of your program's memory to a stranger. The techniques below, bounded readers, explicit limits and early rejection, exist to make that mistake structurally hard.
Bytes, byte order and a reader that cannot overrun
The foundation is reading integers out of a buffer. This is where the first category of bugs lives: reading past the end, reading with the wrong byte order, and relying on undefined behaviour that happens to work on your machine. A protocol field is a sequence of bytes in a defined order. Network protocols use big-endian, so the most significant byte comes first. The portable and safe way to read one is to assemble it from single bytes with explicit shifts, casting each byte to an unsigned type first so the promotion to int cannot push a bit into the sign position.
#ifndef READER_H
#define READER_H
#include <stddef.h>
#include <stdint.h>
struct reader {
const uint8_t *p;
size_t left;
int ok;
};
static inline void rd_init(struct reader *r, const void *buf, size_t n)
{
r->p = buf;
r->left = n;
r->ok = 1;
}
static inline int rd_need(struct reader *r, size_t n)
{
if (!r->ok || n > r->left) {
r->ok = 0;
return 0;
}
return 1;
}
static inline uint8_t rd_u8(struct reader *r)
{
if (!rd_need(r, 1))
return 0;
r->left -= 1;
return *r->p++;
}
static inline uint16_t rd_be16(struct reader *r)
{
if (!rd_need(r, 2))
return 0;
uint16_t v = (uint16_t)((uint16_t)r->p[0] << 8 | r->p[1]);
r->p += 2;
r->left -= 2;
return v;
}
static inline uint32_t rd_be32(struct reader *r)
{
if (!rd_need(r, 4))
return 0;
uint32_t v = (uint32_t)r->p[0] << 24 | (uint32_t)r->p[1] << 16 |
(uint32_t)r->p[2] << 8 | (uint32_t)r->p[3];
r->p += 4;
r->left -= 4;
return v;
}
static inline const uint8_t *rd_bytes(struct reader *r, size_t n)
{
if (!rd_need(r, n))
return NULL;
const uint8_t *out = r->p;
r->p += n;
r->left -= n;
return out;
}
#endifEvery accessor checks before it reads, and the check is a single comparison n > left that cannot overflow, because left is a real count of remaining bytes and n is compared directly against it. The reader has a sticky failure flag: once any read fails, ok is cleared and every later read returns zero without advancing. That lets a parser read a dozen fields in a row and test ok once at the end, instead of checking after each one, and a short buffer can never produce a half-valid result.
Use it on the 12-byte header of a DNS message. The bytes are an identifier, a flags word and four counts, each 16 bits:
#include <stdio.h>
#include "reader.h"
int main(void)
{
const uint8_t msg[] = { 0x12, 0x34, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00 };
struct reader r;
rd_init(&r, msg, sizeof msg);
uint16_t id = rd_be16(&r), flags = rd_be16(&r);
uint16_t qd = rd_be16(&r), an = rd_be16(&r);
uint16_t ns = rd_be16(&r), ar = rd_be16(&r);
if (!r.ok) {
puts("truncated header");
return 1;
}
printf("id=0x%04x flags=0x%04x qdcount=%u ancount=%u nscount=%u arcount=%u\n",
id, flags, qd, an, ns, ar);
return 0;
}id=0x1234 flags=0x8180 qdcount=1 ancount=1 nscount=0 arcount=0Feed the same code a buffer of eleven bytes and the last rd_be16 fails, ok clears and the program prints truncated header instead of reading a byte that is not there. Notice what the reader never does: it never casts a byte pointer to a uint16_t *. That cast looks shorter and has three problems at once, since the address may not be aligned, the read violates strict aliasing and the result is in the host's byte order. Assembling from bytes has none of them, and compilers turn the shifts into efficient code on architectures where an unaligned load is cheap.
Framing: knowing where a message ends
TCP delivers a stream. A sender that writes three messages may be read as one chunk, as a hundred, or as a chunk that ends in the middle of the second message. Framing is the part of the protocol that lets the receiver recover the message boundaries, and there are three common designs.
Length prefix. Each message starts with its size, as in DNS over TCP, TLS records and most binary protocols. It is simple and fast, and the receiver needs only to buffer until it has the length and then that many bytes. The danger is trusting the length, so every parser of this kind needs a maximum.
Delimiter. Messages end with a marker, usually a line terminator, as in SMTP, HTTP headers and Redis inline commands. It is human readable and easy to debug, and it requires scanning every byte for the delimiter and a bound on how far to look.
Fixed size. Every message has the same length, as with some telemetry and legacy formats. It is the simplest of all, and it breaks as soon as you need a variable field.
Whichever you choose, the receiver must be written as an incremental parser: a state machine that is fed whatever bytes arrived and remembers where it stopped. Calling recv once and expecting a whole message works on loopback and fails on a real network. Here is the length-prefixed design in full, a parser for messages made of a two-byte length and that many payload bytes, up to a maximum of 1,024.
#ifndef FRAME_PARSER_H
#define FRAME_PARSER_H
#include <stddef.h>
#include <stdint.h>
#define FRAME_MAX 1024
enum fstate { F_LEN_HI, F_LEN_LO, F_PAYLOAD, F_ERROR };
struct frame_parser {
enum fstate state;
uint16_t length, filled;
uint8_t payload[FRAME_MAX];
};
typedef void (*frame_cb)(const uint8_t *payload, uint16_t len, void *ctx);
void fp_init(struct frame_parser *p);
int fp_feed(struct frame_parser *p, const uint8_t *d, size_t n, frame_cb cb, void *ctx);
#endif#include <string.h>
#include "frame_parser.h"
void fp_init(struct frame_parser *p)
{
p->state = F_LEN_HI;
p->length = p->filled = 0;
}
int fp_feed(struct frame_parser *p, const uint8_t *d, size_t n, frame_cb cb, void *ctx)
{
size_t i = 0;
while (i < n) {
switch (p->state) {
case F_LEN_HI:
p->length = (uint16_t)(d[i++] << 8);
p->state = F_LEN_LO;
break;
case F_LEN_LO:
p->length |= d[i++];
if (p->length > FRAME_MAX) {
p->state = F_ERROR;
return -1;
}
p->filled = 0;
if (p->length == 0) {
cb(p->payload, 0, ctx);
p->state = F_LEN_HI;
} else {
p->state = F_PAYLOAD;
}
break;
case F_PAYLOAD: {
size_t want = (size_t)p->length - p->filled;
size_t have = n - i;
size_t take = want < have ? want : have;
memcpy(p->payload + p->filled, d + i, take);
p->filled += (uint16_t)take;
i += take;
if (p->filled == p->length) {
cb(p->payload, p->length, ctx);
p->state = F_LEN_HI;
}
break;
}
case F_ERROR:
return -1;
}
}
return 0;
}Drive it with a stream of two messages, hello and ok, fed in awkward chunks. The test splits the stream at a position inside the first length field and again inside the first payload:
#include <stdio.h>
#include "frame_parser.h"
static void show(const uint8_t *payload, uint16_t len, void *ctx)
{
(void)ctx;
printf("message (%u bytes): %.*s\n", len, (int)len, (const char *)payload);
}
int main(void)
{
struct frame_parser p;
const uint8_t stream[] = { 0, 5, 'h', 'e', 'l', 'l', 'o', 0, 2, 'o', 'k' };
fp_init(&p);
fp_feed(&p, stream, 1, show, NULL); /* half a length field */
fp_feed(&p, stream + 1, 4, show, NULL); /* rest of it, 3 payload bytes */
fp_feed(&p, stream + 5, sizeof stream - 5, show, NULL); /* everything else */
return 0;
}message (5 bytes): hello
message (2 bytes): okThe three chunks, 1, 4 and 6 bytes, deliver the same two messages that a single 11-byte call would. That equivalence, that any chunking of the same stream produces the same messages, is the defining property of a correct incremental parser, and it is the property you test later. The length check happens the moment the second length byte arrives, before any payload is accepted, so a peer cannot make the parser buffer more than FRAME_MAX bytes. Memory use is fixed and no allocation happens on the hot path. Nothing in the parser blocks or reads a socket. It consumes bytes, calls back, and returns.
Text protocols and the delimiter problem
Line-oriented protocols have their own incremental parser, with their own hazards. The rule that terminates a line in most internet protocols is a carriage return followed by a line feed. Treating a bare line feed as a terminator, a tempting leniency, is the root of a family of request-smuggling and injection bugs, because two systems that disagree about where a line ends can be made to disagree about what a message says. The strict parser accepts only the two-byte sequence, rejects anything else, and bounds the line length.
#ifndef LINE_PARSER_H
#define LINE_PARSER_H
#include <stddef.h>
#define LINE_MAX 512
struct line_parser {
char buf[LINE_MAX];
size_t used;
int saw_cr;
};
typedef void (*line_cb)(const char *line, void *ctx);
int line_feed(struct line_parser *p, const char *d, size_t n, line_cb cb, void *ctx);
#endif#include "line_parser.h"
int line_feed(struct line_parser *p, const char *d, size_t n, line_cb cb, void *ctx)
{
for (size_t i = 0; i < n; i++) {
char c = d[i];
if (p->saw_cr) {
p->saw_cr = 0;
if (c != '\n')
return -1; /* CR must be followed by LF */
p->buf[p->used] = '\0';
cb(p->buf, ctx);
p->used = 0;
continue;
}
if (c == '\r') {
p->saw_cr = 1;
continue;
}
if (c == '\n')
return -1; /* bare LF is not a terminator */
if (p->used + 1 >= sizeof p->buf)
return -1; /* line too long */
p->buf[p->used++] = c;
}
return 0;
}#include <stdio.h>
#include <string.h>
#include "line_parser.h"
static void got(const char *line, void *ctx)
{
(void)ctx;
printf("command: %s\n", line);
}
int main(void)
{
struct line_parser p;
memset(&p, 0, sizeof p);
line_feed(&p, "HELO exa", 8, got, NULL);
line_feed(&p, "mple\r", 5, got, NULL);
line_feed(&p, "\nQUIT\r\n", 7, got, NULL);
char big[600];
memset(big, 'x', sizeof big);
printf("long line: %s\n", line_feed(&p, big, sizeof big, got, NULL) < 0 ? "rejected" : "accepted");
return 0;
}command: HELO example
command: QUIT
long line: rejectedThe carriage return arrived at the end of one chunk and its line feed at the start of the next, which is why the parser keeps saw_cr as state instead of looking ahead in the current buffer. A parser that scans each chunk for the two-byte sequence misses every terminator that straddles a read boundary, and the bug appears only under real network conditions. The LINE_MAX limit is the equivalent of the frame size limit: SMTP's own specification caps a command line at 512 bytes including the terminator, and HTTP servers conventionally cap the request line and header block, since an unbounded line is an unbounded buffer.
Decoding a real format: DNS with name compression
Framing gets you a message. Parsing a real message format shows the second class of hazard, structures that refer to other parts of the same buffer. DNS is the classic example, because it compresses domain names by letting a name end in a pointer back to an earlier name. A decoder must follow the pointer, and a pointer is a number from the wire, so it can point anywhere, including at itself.
A DNS name on the wire is a sequence of labels, each a length byte followed by that many characters, ending with a zero byte. A length byte whose top two bits are set is not a length but the first byte of a two-byte pointer holding a 14-bit offset from the start of the message. The decoder below follows pointers with a hop limit and checks every offset, and it returns where the name ended in the original position, which is what the caller needs to continue parsing.
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/* Decodes the name at pos into out. On success sets *next to the first byte after
* the name at its original position (not after any pointer target). */
int dns_name(const uint8_t *msg, size_t len, size_t pos,
char *out, size_t cap, size_t *next)
{
size_t o = 0, end = 0;
int jumped = 0, hops = 0;
for (;;) {
if (pos >= len)
return -1;
uint8_t b = msg[pos];
if (b == 0) {
if (!jumped)
end = pos + 1;
break;
}
if ((b & 0xc0) == 0xc0) {
if (pos + 1 >= len)
return -1;
size_t target = (size_t)(b & 0x3f) << 8 | msg[pos + 1];
if (!jumped)
end = pos + 2;
if (++hops > 16 || target >= len)
return -1;
pos = target;
jumped = 1;
continue;
}
if (b > 63 || pos + 1 + b > len)
return -1;
size_t need = o + (o ? 1 : 0) + b + 1;
if (need > cap)
return -1;
if (o)
out[o++] = '.';
memcpy(out + o, msg + pos + 1, b);
o += b;
pos += 1 + b;
}
out[o] = '\0';
*next = end;
return 0;
}Now a complete response for an A query, 45 bytes, with the answer's name compressed to a pointer at offset 12, where the question's name begins:
#include <stdint.h>
#include <stdio.h>
int dns_name(const uint8_t *msg, size_t len, size_t pos, char *out, size_t cap, size_t *next);
int main(void)
{
const uint8_t msg[] = {
0x12, 0x34, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', 0, 0, 1, 0, 1,
0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0x0e, 0x10, 0, 4, 192, 0, 2, 80
};
char name[64];
size_t pos = 12, next;
if (dns_name(msg, sizeof msg, pos, name, sizeof name, &next) < 0)
return 1;
printf("question: %s\n", name);
pos = next + 4; /* skip QTYPE and QCLASS */
if (dns_name(msg, sizeof msg, pos, name, sizeof name, &next) < 0)
return 1;
pos = next;
unsigned ttl = (unsigned)msg[pos + 4] << 24 | msg[pos + 5] << 16 | msg[pos + 6] << 8 | msg[pos + 7];
printf("answer: %s A %u.%u.%u.%u ttl=%u\n", name,
msg[pos + 10], msg[pos + 11], msg[pos + 12], msg[pos + 13], ttl);
const uint8_t loop[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0x0c };
printf("pointer loop: %s\n",
dns_name(loop, sizeof loop, 12, name, sizeof name, &next) < 0 ? "rejected" : "accepted");
return 0;
}question: example.com
answer: example.com A 192.0.2.80 ttl=3600
pointer loop: rejectedThe last message is 14 bytes whose name at offset 12 is a pointer to offset 12, an infinite loop. The hop counter stops it after 16 jumps. Without the counter, the decoder would spin forever on a single 14-byte datagram, which is a denial of service you could trigger from anywhere on the internet. The same decoder shows another habit worth copying: next is the end of the name at its original position, so after a compressed name it is two bytes past the pointer, and the caller continues from the right place whatever the pointer pointed to.
Parse, then validate, then act
A parser that reads the structure correctly has done a third of the job. The rest is deciding whether the message makes sense, and keeping that separate from parsing pays off. A good rule is that the parser produces a typed structure and nothing else, and a separate function checks the semantic rules and returns a reason for any rejection, so tests can assert on the reason.
Semantic rules are protocol specific. A DNS response must have its response bit set and a matching identifier. A TCP segment's data offset must be at least five words and no more than the segment. An IPv4 header's total length must cover its own header, and its checksum must verify. These are cheap to check and are the difference between a parser and a safe parser, because the later layers assume the invariants hold.
The IPv4 header checksum is a good example of a check with a self-verifying property. The checksum is the ones'-complement of the ones'-complement sum of the header as 16-bit words, so summing a valid header, checksum field included, gives all ones, and inverting that gives zero. The function that computes a checksum is also the one that verifies it.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
uint16_t inet_checksum(const void *data, size_t len)
{
const uint8_t *p = data;
uint32_t sum = 0;
for (; len > 1; p += 2, len -= 2)
sum += (uint32_t)(p[0] << 8 | p[1]);
if (len)
sum += (uint32_t)(p[0] << 8);
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return (uint16_t)~sum;
}
struct ip_result { int ok; const char *why; };
struct ip_result ip_validate(const uint8_t *pkt, size_t len)
{
if (len < 20)
return (struct ip_result){ 0, "shorter than a minimal header" };
if ((pkt[0] >> 4) != 4)
return (struct ip_result){ 0, "not IPv4" };
size_t ihl = (size_t)(pkt[0] & 0x0f) * 4;
size_t total = (size_t)(pkt[2] << 8 | pkt[3]);
if (ihl < 20 || ihl > len)
return (struct ip_result){ 0, "bad header length" };
if (total < ihl || total > len)
return (struct ip_result){ 0, "bad total length" };
if (inet_checksum(pkt, ihl) != 0)
return (struct ip_result){ 0, "checksum mismatch" };
return (struct ip_result){ 1, "ok" };
}
int main(void)
{
uint8_t hdr[20] = { 0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11,
0xb8, 0x61, 0xc0, 0xa8, 0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7 };
uint8_t padded[0x73] = { 0 };
for (int i = 0; i < 20; i++)
padded[i] = hdr[i];
printf("valid header: %s\n", ip_validate(padded, sizeof padded).why);
padded[8] = 0x3f; /* change the TTL, keep the old checksum */
printf("corrupted TTL: %s\n", ip_validate(padded, sizeof padded).why);
printf("truncated: %s\n", ip_validate(padded, 10).why);
return 0;
}valid header: ok
corrupted TTL: checksum mismatch
truncated: shorter than a minimal headerThe header bytes are a well-known worked example: summing its ten 16-bit words, with end-around carry, yields 0xffff, so the inverted result is zero and the header is valid. Changing one byte without updating the checksum breaks the sum, which is exactly how a bit flip on the wire is detected. The order of the checks matters. Length checks come first, because the checksum reads ihl bytes and must not be asked to read past the buffer. Returning a reason, not a bare failure, is what makes the tests meaningful: a test that says "rejected" for the wrong reason has not tested what you think it has.
Resource limits are part of the protocol
A parser that is memory safe can still be taken down. Security failures in parsers fall into two groups, memory corruption, which bounds checks prevent, and resource exhaustion, which only limits prevent. A message can be perfectly well-formed and still cost you more than you can afford: a name with a thousand labels, a list with a million entries, a decompression ratio of a thousand to one, a request that makes you do quadratic work.
Every loop driven by a wire value needs a budget. The DNS decoder's hop limit is one. Others to decide up front are the maximum message size, the maximum number of entries in any list, the maximum nesting depth of recursive structures, the maximum time a connection may spend in a partial state, and the maximum memory any one peer may hold. Choose the numbers from the protocol's own limits where it has them, and from your capacity where it does not.
Arithmetic on wire values deserves the same suspicion, because the product of two attacker-controlled numbers overflows without warning. GCC and Clang provide checked arithmetic builtins that report the overflow instead of hiding it:
#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint32_t count = 0x20000001u, entry_size = 8u;
uint32_t naive = count * entry_size; /* wraps around */
uint32_t checked;
int overflowed = __builtin_mul_overflow(count, entry_size, &checked);
printf("naive product: %u bytes\n", naive);
printf("checked: %s\n", overflowed ? "overflow, reject the message" : "ok");
return 0;
}naive product: 8 bytes
checked: overflow, reject the messageAn allocation of 8 bytes followed by a loop that writes 536 million entries is the textbook heap overflow, and it comes from exactly this multiplication. The same builtins exist for addition and subtraction, and the rule that goes with them is to do the check before the allocation, never after. Where a protocol allows large values for legitimate reasons, compare the claimed size against what could possibly fit in the remaining input: a list of count entries each at least entry_size bytes cannot be in a message shorter than their product, and testing that cheap fact first rejects the hostile case without computing anything dangerous.
State machines for stateful protocols
A stateless parser reads a message and is done. Most protocols are not stateless. What is legal depends on what has already happened: a TCP segment with data is fine in ESTABLISHED and an error in LISTEN, and an SMTP DATA command before a MAIL FROM is out of sequence. The structure that captures this is a finite state machine, and the most reliable way to write one in C is as a table, because a table makes illegal combinations visible as gaps and makes the whole behaviour reviewable at a glance.
Below is the passive-open half of the TCP connection lifecycle from RFC 9293: a server in LISTEN receives a SYN, answers, gets the final ACK, later receives a FIN, and closes. Each transition names the next state and the action to take.
#include <stdio.h>
enum st { CLOSED, LISTEN, SYN_RCVD, ESTABLISHED, CLOSE_WAIT, LAST_ACK, NSTATE };
enum ev { EV_SYN, EV_ACK, EV_FIN, EV_CLOSE, NEV };
struct trans {
enum st next;
const char *action; /* NULL means: no transition defined */
};
static const struct trans T[NSTATE][NEV] = {
[LISTEN] = { [EV_SYN] = { SYN_RCVD, "send SYN+ACK" } },
[SYN_RCVD] = { [EV_ACK] = { ESTABLISHED, "none" } },
[ESTABLISHED] = { [EV_FIN] = { CLOSE_WAIT, "send ACK" } },
[CLOSE_WAIT] = { [EV_CLOSE] = { LAST_ACK, "send FIN" } },
[LAST_ACK] = { [EV_ACK] = { CLOSED, "free connection" } },
};
static const char *SN[] = { "CLOSED", "LISTEN", "SYN_RCVD", "ESTABLISHED",
"CLOSE_WAIT", "LAST_ACK" };
static const char *EN[] = { "SYN", "ACK", "FIN", "CLOSE" };
int main(void)
{
enum ev script[] = { EV_SYN, EV_ACK, EV_FIN, EV_CLOSE, EV_ACK, EV_ACK };
enum st s = LISTEN;
for (size_t i = 0; i < sizeof script / sizeof script[0]; i++) {
const struct trans *t = &T[s][script[i]];
if (t->action == NULL) {
printf("%s + %s: no transition, dropped\n", SN[s], EN[script[i]]);
continue;
}
printf("%s + %s -> %s: %s\n", SN[s], EN[script[i]], SN[t->next], t->action);
s = t->next;
}
return 0;
}LISTEN + SYN -> SYN_RCVD: send SYN+ACK
SYN_RCVD + ACK -> ESTABLISHED: none
ESTABLISHED + FIN -> CLOSE_WAIT: send ACK
CLOSE_WAIT + CLOSE -> LAST_ACK: send FIN
LAST_ACK + ACK -> CLOSED: free connection
CLOSED + ACK: no transition, droppedThe unfilled cells of the table are the interesting part. Every event the table does not list for a state falls to the same default, drop and, for protocols that specify it, answer with a reset. Compare that with a tangle of if statements on boolean flags, where each new feature adds a flag and the number of reachable combinations doubles. In the table design, adding a state adds a row, and reading the table tells you every behaviour the machine has. The model here is deliberately partial, and a full TCP also needs the active-open states, FIN_WAIT_1 and FIN_WAIT_2, CLOSING and TIME_WAIT, but the structure is the same.
A state machine also carries timers. A connection in SYN_RCVD that never receives its ACK must eventually be freed, or a flood of spoofed SYN packets fills memory with half-open connections. So each state that waits on the peer needs a deadline, and expiry is just another event, EV_TIMEOUT, fed into the same table. Treating time as an event keeps the machine deterministic and testable: a test advances a fake clock and checks the transitions, without sleeping.
Packet buffers: building headers without copying
From here on the guide moves from parsing to building a stack, and the first decision is how packets are stored. A naive stack allocates a buffer for each layer, copying the payload down as each header is added. That is slow and, worse, it makes every layer allocate. Real stacks use a single buffer with spare room at the front, called headroom, so each layer prepends its header by moving a pointer backwards. The payload never moves.
The same idea is called sk_buff in Linux, pbuf in lwIP and mbuf in BSD and DPDK. A minimal version needs only a buffer, a start offset and a length, and two operations: append at the tail, and prepend at the head.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
struct pkt {
uint8_t buf[256];
size_t head; /* offset of the first valid byte */
size_t len; /* number of valid bytes */
};
void pkt_init(struct pkt *p, size_t headroom)
{
p->head = headroom;
p->len = 0;
}
uint8_t *pkt_put(struct pkt *p, size_t n) /* append at the tail */
{
if (p->head + p->len + n > sizeof p->buf)
return NULL;
uint8_t *r = p->buf + p->head + p->len;
p->len += n;
return r;
}
uint8_t *pkt_push(struct pkt *p, size_t n) /* prepend at the head */
{
if (n > p->head)
return NULL;
p->head -= n;
p->len += n;
return p->buf + p->head;
}
int main(void)
{
struct pkt p;
pkt_init(&p, 64); /* room for all headers */
memcpy(pkt_put(&p, 2), "hi", 2); /* UDP payload */
memset(pkt_push(&p, 8), 0, 8); /* UDP header */
memset(pkt_push(&p, 20), 0, 20); /* IPv4 header */
memset(pkt_push(&p, 14), 0, 14); /* Ethernet header */
printf("frame length %zu, starts at buffer offset %zu\n", p.len, p.head);
return 0;
}frame length 44, starts at buffer offset 22The headroom of 64 bytes covers the 42 bytes of headers a UDP packet over IPv4 over Ethernet needs, so three pkt_push calls produce a contiguous 44-byte frame, and the two payload bytes were written once and never moved. Both functions check their bounds and return NULL instead of writing out of range, which is the buffer-level version of the bounded reader. The receive path uses the mirror operation: as each layer finishes with its header it advances head and shrinks len, so the next layer sees the payload as if it were the whole packet, again with no copy. Choose the headroom for the deepest stack you will build, including tunnels and VLAN tags, because a push that does not fit is an error you do not want to meet in production.
Layers: how a stack is organised
With a buffer type, a stack is a set of functions with one shape: each layer takes a packet and either processes it or passes it to the next layer, in the receive direction, and builds a header and passes down in the transmit direction. The receive entry point is a function that looks at the Ethernet type and dispatches. A good way to stay sane is to write each layer as a pure function of its input bytes, returning the bytes to send in reply, with all side effects done by a thin driver loop around it.
ARP is the smallest such function and shows the pattern. It receives a frame, decides whether it is a request for our address, and builds a reply into a separate buffer. It performs no I/O.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static const uint8_t MY_MAC[6] = { 0x02, 0, 0, 0, 0, 0x02 };
static const uint8_t MY_IP[4] = { 10, 0, 0, 2 };
/* Returns the reply length written to out (at least 42 bytes), or 0 for no reply. */
size_t arp_reply(const uint8_t *in, size_t n, uint8_t *out)
{
if (n < 42 || in[12] != 0x08 || in[13] != 0x06)
return 0;
const uint8_t *a = in + 14;
if (a[7] != 1 || memcmp(a + 24, MY_IP, 4) != 0) /* request for our address? */
return 0;
memcpy(out, in + 6, 6);
memcpy(out + 6, MY_MAC, 6);
out[12] = 0x08; out[13] = 0x06;
memcpy(out + 14, a, 6);
out[20] = 0; out[21] = 2; /* operation: reply */
memcpy(out + 22, MY_MAC, 6);
memcpy(out + 28, MY_IP, 4);
memcpy(out + 32, a + 8, 6);
memcpy(out + 38, a + 14, 4);
return 42;
}
int main(void)
{
uint8_t req[42] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0, 0, 0, 0, 0x01,
0x08, 0x06, 0, 1, 8, 0, 6, 4, 0, 1,
0x02, 0, 0, 0, 0, 0x01, 10, 0, 0, 1,
0, 0, 0, 0, 0, 0, 10, 0, 0, 2 };
uint8_t out[64];
size_t n = arp_reply(req, sizeof req, out);
printf("reply length %zu, operation %u, sender ip %u.%u.%u.%u\n",
n, out[21], out[28], out[29], out[30], out[31]);
req[41] = 9; /* ask for 10.0.0.9 instead */
printf("other address: %zu bytes\n", arp_reply(req, sizeof req, out));
return 0;
}reply length 42, operation 2, sender ip 10.0.0.2
other address: 0 bytesBecause arp_reply is a pure function of its input, the test needs no network device, no root and no timing. The driver loop that reads from a TAP device and writes the reply is five lines and has nothing to get wrong. Build every layer this way, ICMP echo, UDP demultiplexing and the TCP segment handler, and the whole stack can be tested by feeding it captured frames and comparing the output bytes with the expected ones. A packet capture from a real exchange becomes a regression test: replay it through the stack and assert on what comes out.
The one layer that cannot be a pure function is TCP, because it owns state across packets, a table of connections keyed by the four-tuple of addresses and ports, with the state machine from the previous section, sequence-number tracking, timers and buffers. Even there, keep the shape: tcp_input(conn_table, segment, now) returns a list of actions, send these segments, deliver this data, arm this timer, and the driver carries them out. The retransmission and congestion control logic that sits on top is covered in its own post in this series.
I/O: sockets, TAP devices and event loops
The driver loop connects the pure layers to the outside world, and the choice of I/O mechanism sets the structure of the program. There are three common mechanisms for a parser or stack to read from.
A socket is the right interface for a parser inside an application: the kernel runs the lower layers and you parse the stream or datagrams it delivers. Use blocking calls for a tool, and non-blocking calls with epoll for a server. The rule for non-blocking reads is to read until EAGAIN, feed every byte to the incremental parser and never assume one read is one message.
A TAP device is the right interface for building a stack of your own on Linux. It hands you whole Ethernet frames and accepts whole frames, so you implement everything above the NIC. It is the subject of its own post, and it gives you a real network to test against, since the host's kernel and tools such as ping and tcpdump talk to your stack through it.
A packet socket or a kernel-bypass interface such as AF_XDP or DPDK hands you frames at high rate and is for stacks that must run at line speed.
The epoll loop for a socket-based protocol server has a fixed shape, shown here for the framed protocol above. Each connection owns a parser, and the loop reads whatever is available and feeds it:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
struct conn { int fd; /* plus a struct frame_parser in a real server */ };
static void on_readable(struct conn *c)
{
unsigned char buf[4096];
for (;;) {
ssize_t n = recv(c->fd, buf, sizeof buf, 0);
if (n > 0) {
/* fp_feed(&c->parser, buf, n, handle_frame, c); on -1: close */
continue;
}
if (n == 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
close(c->fd); /* peer closed, or a real error */
free(c);
}
return; /* EAGAIN: drained, wait for the next event */
}
}
void run(int listen_fd)
{
int ep = epoll_create1(0);
struct epoll_event ev = { .events = EPOLLIN, .data.ptr = NULL };
epoll_ctl(ep, EPOLL_CTL_ADD, listen_fd, &ev);
for (;;) {
struct epoll_event events[64];
int n = epoll_wait(ep, events, 64, -1);
for (int i = 0; i < n; i++) {
if (events[i].data.ptr == NULL) {
int fd = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK);
if (fd < 0)
continue;
struct conn *c = calloc(1, sizeof *c);
c->fd = fd;
struct epoll_event cev = { .events = EPOLLIN, .data.ptr = c };
epoll_ctl(ep, EPOLL_CTL_ADD, fd, &cev);
} else {
on_readable(events[i].data.ptr);
}
}
}
}The inner for (;;) in on_readable is the part to understand. With level-triggered epoll you could read once per event, but reading until EAGAIN makes the code correct under edge-triggered mode too, and it ensures that one connection with a large backlog is fully drained. A fairness cap, a maximum number of reads per event, stops a fast sender from monopolising the loop. The parser state lives in the connection struct, so each peer's partial message waits there between events.
Testing: split inputs, golden captures and properties
A network parser is unusually easy to test because it is a function of bytes, and unusually easy to test badly because the failures live in inputs nobody thought of. A good test suite for a parser has four layers.
Example tests feed known messages and check the parsed result, including the boundary values: empty messages, maximum-size messages, a length one past the maximum, and a truncation at every possible byte.
Split tests check the incremental property. Feed the same stream in one call, in single bytes and cut at every offset, and assert that the messages produced are identical. This is the test that finds the straddling-terminator bug and the half-a-length-field bug, and it is a short loop:
#include <stdio.h>
#include "frame_parser.h"
static void count(const uint8_t *payload, uint16_t len, void *ctx)
{
(void)payload; (void)len;
++*(int *)ctx;
}
int main(void)
{
const uint8_t stream[] = { 0, 3, 'a', 'b', 'c', 0, 0, 0, 1, 'z' };
int failures = 0;
for (size_t split = 0; split <= sizeof stream; split++) {
struct frame_parser p;
int messages = 0;
fp_init(&p);
fp_feed(&p, stream, split, count, &messages);
fp_feed(&p, stream + split, sizeof stream - split, count, &messages);
if (messages != 3)
failures++;
}
printf("%zu splits, %d failures\n", sizeof stream + 1, failures);
return failures != 0;
}11 splits, 0 failuresThe stream holds three messages, abc, an empty message and z, so each of the 11 split positions must yield exactly three callbacks. Golden tests take real captures of the protocol, from tcpdump or the specification's own examples, and check that the parser accepts them and reproduces known field values. They protect against the failure where your parser and your encoder agree with each other and both disagree with the real world. Property tests generate random valid messages, serialise them, parse them back and check that the result equals the input, and generate random garbage and check that the parser never crashes and never reads out of bounds.
Run everything under AddressSanitizer and UndefinedBehaviorSanitizer, with -fsanitize=address,undefined. A parser that passes its tests without sanitizers may still be reading one byte past a buffer, and only the sanitizer will say so.
Fuzzing the parsers
Hand-written tests find the failures you can imagine. A coverage-guided fuzzer finds the ones you cannot. libFuzzer, included with Clang, runs your parser in-process on mutated inputs and keeps any input that reaches new code, which lets it discover a protocol's structure by exploration. The harness is a single function, and for a parser it is short:
#include <stddef.h>
#include <stdint.h>
int dns_name(const uint8_t *msg, size_t len, size_t pos, char *out, size_t cap, size_t *next);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
char name[256];
size_t next;
for (size_t pos = 0; pos < size && pos < 32; pos++)
dns_name(data, size, pos, name, sizeof name, &next);
return 0;
}Build it with clang -g -O1 -fsanitize=fuzzer,address,undefined fuzz_dns.c dns_name.c -o fuzz_dns and run ./fuzz_dns corpus/. The harness tries the decoder at several offsets of every input, which multiplies the paths a single input exercises. Seed the corpus with real messages so the fuzzer starts past the header checks. For stream parsers, derive the chunk sizes from the input itself so the fuzzer explores splits as well as contents, which is how it finds the boundary bugs that tests with fixed splits miss. Treat every crash file as a permanent regression test and keep it in the repository.
Performance: where the time goes
Optimise a protocol implementation last, and with measurements, because the obvious guesses are usually wrong. Three costs dominate in practice, and they are worth knowing in order.
The first is system calls and context switches. A server that reads one message per recv and writes one reply per send spends most of its time entering the kernel. Batching, with larger reads that feed many messages to the parser, recvmmsg and sendmmsg for datagrams, and writev or one buffered send per connection per loop iteration, removes most of it.
The second is copying. Parse in place, and keep the parsed fields as views into the receive buffer instead of copies. A view is a pointer and a length, and a header view costs nothing to create:
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
struct view { const uint8_t *p; size_t n; };
struct view slice(struct view v, size_t off, size_t len)
{
if (off > v.n || len > v.n - off)
return (struct view){ NULL, 0 };
return (struct view){ v.p + off, len };
}
int main(void)
{
const uint8_t frame[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 'p', 'a', 'y' };
struct view all = { frame, sizeof frame };
struct view payload = slice(all, 14, 3);
struct view bad = slice(all, 14, 4);
printf("payload: %zu bytes at offset %td\n", payload.n, payload.p - frame);
printf("out of range slice: %s\n", bad.p == NULL ? "rejected" : "accepted");
return 0;
}payload: 3 bytes at offset 14
out of range slice: rejectedThe views never copy and slice is the bounds check, with the same overflow-safe form as the reader. The caveat is lifetime: a view is valid only while the buffer it points into is, so a parser that hands views to application code must say how long they last, usually until the next read on that connection. The third cost is the cache. Keep per-connection state small and contiguous, avoid pointer chasing in the hot path, and size tables as powers of two so lookups are a mask, not a division. Past those, the kernel offers offloads that move work off the CPU, such as checksum and segmentation offload, and bypass paths that avoid the stack, and each is its own subject in this series.
Versions, extensions and unknown fields
A protocol that lives for years changes, and the way a parser treats what it does not recognise decides whether those changes are painless or breaking. There are two opposite failure modes. A parser that rejects anything unfamiliar makes every extension a flag day, since old software refuses new messages. A parser that silently accepts anything unfamiliar can be fed values it misinterprets, and it hides bugs in the sender that would otherwise be caught early. The protocol's own rules should decide, and good protocols state them.
Three conventions recur. Reserved bits and fields must be sent as zero and ignored on receipt, so they can be given meaning later. The IPv4 header's flags and TCP's reserved bits work this way. Options in type-length-value form, as in TCP options and DNS records, let a receiver skip a kind it does not understand using the length, so the parser needs a generic skip path, bounded by the same limits as everything else. And version fields split into those that select a different format, where an unknown version is an error you report, and those that only advertise capability, where an unknown value is ignored.
Write the unknown-handling policy into the parser deliberately and test it. A test that feeds an option of an unassigned kind with a valid length and expects it to be skipped, and another that feeds one with a length running past the end and expects rejection, pins the behaviour down. Skipping must never mean trusting: a skipped option still has its length checked against the bytes that remain, since the skip is just a pointer advance and an unchecked advance is an out-of-bounds read waiting to happen.
Be careful with canonical forms as well. Where a value has more than one valid encoding, such as a length written with leading padding or a domain name in mixed case, decide which your parser accepts and normalise early. Two components that normalise differently can be made to disagree about the same bytes, which is the mechanism behind many bypass bugs, where a filter in front of an application sees one thing and the application sees another.
Time, timers and testability
Stateful protocols depend on time: retransmission timers, idle timeouts, handshake deadlines and rate limits. The common mistake is to read the system clock directly from protocol code, which makes the code impossible to test without sleeping and impossible to replay deterministically. The fix is to treat time as an input. Pass the current time into every function that needs it, as a plain integer in a fixed unit, and keep all timer bookkeeping in your own data structure, such as a min-heap or a timing wheel, that the driver loop consults.
#include <stdint.h>
#include <stdio.h>
struct timer { uint64_t deadline_ms; int armed; };
int timer_expired(const struct timer *t, uint64_t now_ms)
{
return t->armed && (int64_t)(now_ms - t->deadline_ms) >= 0;
}
int main(void)
{
struct timer syn_rcvd = { .deadline_ms = 1000 + 5000, .armed = 1 };
for (uint64_t now = 1000; now <= 7000; now += 2000)
printf("t=%llu ms: %s\n", (unsigned long long)now,
timer_expired(&syn_rcvd, now) ? "expired, drop half-open connection" : "waiting");
return 0;
}t=1000 ms: waiting
t=3000 ms: waiting
t=5000 ms: waiting
t=7000 ms: expired, drop half-open connectionThe comparison casts the difference to a signed 64-bit value, which is how deadlines are compared safely when the counter wraps. A test can now create a connection, set the fake clock to any value and assert what the stack does, with no real waiting. The driver loop supplies the real time from clock_gettime(CLOCK_MONOTONIC), and uses the nearest deadline as the timeout to epoll_wait, so the program sleeps exactly until something needs doing. Always use a monotonic clock for these timers, since the wall clock can jump backwards when it is adjusted and would make timers fire early or never.
Observability: counters before logs
When a parser rejects a message, the question that follows is why and how often, and the answer should not require attaching a debugger to production. Build observability in from the start, and make the cheap form the default. Counters cost one increment and survive load. Keep one per rejection reason: truncated header, bad length, checksum mismatch, unknown version, limit exceeded. Export them through whatever your program already uses for metrics. A sudden rise in one tells you what changed, whether a new client with a bug, a scan, or an attack, with no per-packet cost.
Logs are for the rare events and need rate limiting, because a malformed-packet flood becomes a log flood and can fill a disk or hide the interesting line. Log the first occurrence of each reason per peer and then summarise. Include enough context to reproduce the failure, the peer address, the state of the connection and the first few bytes of the offending message in hex, and never log secrets or full payloads. For stacks, a packet capture facility, a hook that writes frames to a file in the standard capture format, is worth more than any amount of logging, because it lets you open the exchange in the same tools you use for real traffic.
Security checklist
Parsers are where networks meet attackers, so it is worth ending the technical sections with a list to check a design against. Each item is a failure that has shipped in real software.
Every read is bounds-checked against the remaining input, with comparisons that cannot overflow.
No length from the wire sizes an allocation or bounds a loop until it has been compared with a limit.
Arithmetic on wire values uses checked builtins, or is done in a wider type with an explicit range check.
Every loop and recursion has a budget: hops, depth, entries, total work.
Back-references and pointers are validated and cycle-bounded.
Line and message terminators are strict, with no leniency that two implementations could disagree on.
Unknown or unexpected input is rejected, not guessed at, and a protocol error closes the connection.
Half-open and idle connections time out, and the number of connections and bytes per peer is capped.
Replies are never larger than requests without authentication, to avoid becoming an amplifier for spoofed traffic.
Secrets and keys are never logged, and errors reveal no more than the peer needs to know.
Everything is tested under sanitizers and fuzzed continuously, with crash files kept as regression tests.
Choosing tools: C, Rust and generators
C gives you control and nothing else, and every safety property above is a discipline you maintain by hand. That is workable with a small, well-reviewed reader and a strict habit of using it, and it is also why a large share of historical network vulnerabilities are in C parsers. Rust turns most of the memory-safety items on the list into compiler guarantees, and libraries such as nom make incremental parsing a matter of combining small functions, with a Needed result to say how much more input to wait for. The cost is a different style and a toolchain, and the resource-limit and logic items remain your job in either language.
Parser generators and interface description languages are the third option. For a binary format with a formal description, generating the parser from the description removes the hand-written offsets, and for text formats a grammar and a tested parser library does the same. The trade-off is another build step and the fit of the generated code to your constraints, such as no heap allocation on an embedded target.
For the stack itself, the honest advice is to write one to learn and to use an existing one in production. lwIP on microcontrollers, the Linux kernel stack on servers and a mature userspace stack such as DPDK-based ones for line-rate work have years of corner cases that a new implementation will rediscover slowly. Your own parser for your own application protocol is a different matter, and it is the case this guide is mostly about.
A learning path through the topic
If you are working through this material in order, a practical sequence is to start with byte order and a bounded reader, then write an incremental parser for a length-prefixed protocol and test it by splitting at every offset. Next, parse real packet headers from a capture, Ethernet, IPv4 and TCP, and verify the checksums. Then decode DNS, because name compression is the first format where the parser must follow references safely. After that, build a small stack on a TAP device that answers ARP and ICMP, add a UDP echo, and only then attempt TCP, starting with the passive-open states and extending to retransmission and congestion control. Put a fuzzer on every parser as soon as it exists. Each step is small if the previous one is verified, and by the end you will have written the layers that every network program depends on and rarely sees.

