networking · advanced · ~15 min
Decode a 2-byte big-endian length prefix and detect a truncated frame.
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).
buf of n received bytes.
Payload length, or −1 if incomplete.
Need at least 2 bytes for the prefix. A frame is complete only when n >= 2 + declared_length.
#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; }
Reading the length little-endian; using <= instead of < in the truncation check; not handling n<2.
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.