networking · advanced · ~15 min

Read a length-prefixed frame

Decode a 2-byte big-endian length prefix and detect a truncated frame.

Challenge

The client side of a length-prefixed protocol reads the 2-byte prefix, then that many payload bytes. Implement the reader:

int framed_payload_len(const unsigned char *buf, int n);

buf holds the 2-byte big-endian length prefix then the payload. Return the payload length if the buffer is complete (n >= 2 + len), else −1 (the frame is truncated).

Input format

buf of n received bytes.

Output format

Payload length, or −1 if incomplete.

Constraints

Need at least 2 bytes for the prefix. A frame is complete only when n >= 2 + declared_length.

Starter code

#include <stddef.h>
/* buf holds a 2-byte big-endian length prefix then the payload. Return the
   payload length if the buffer is complete (n >= 2 + len), else -1 (truncated). */
int framed_payload_len(const unsigned char *buf, int n){ (void)buf;(void)n; return -1; }

Common mistakes

Reading the length little-endian; using <= instead of < in the truncation check; not handling n<2.

Edge cases to handle

Exactly 2+len bytes → return len; one byte short → −1; extra bytes after the payload are fine.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.