networking · intermediate · ~15 min · safe pentest lab

Frame a length-prefixed message

Serialise a payload with a 2-byte big-endian length prefix.

Challenge

Stream protocols on top of TCP (like an echo server) usually prefix each message with its length so the peer knows where it ends. Implement the framer:

int frame_message(const unsigned char *payload, int len, unsigned char *out);

Write a 2-byte big-endian length prefix followed by the len payload bytes into out; return the total bytes written (len+2), or −1 if len is negative or above 65535.

Why this matters

The traditional first server. Accept one client, read whatever they send, write it back, close.

Input format

payload (may be empty), len in 0..65535, out buffer with room for len+2.

Output format

Total bytes written, or −1.

Constraints

The length prefix is 2 bytes, most-significant byte first. A zero-length payload still writes the 2-byte prefix.

Starter code

#include <stddef.h>
/* Write a 2-byte big-endian length prefix followed by the payload into out.
   Return total bytes written (len+2), or -1 if len<0 or len>65535. */
int frame_message(const unsigned char *payload, int len, unsigned char *out){ (void)payload;(void)len;(void)out; return -1; }

Common mistakes

Writing the length little-endian; forgetting the +2 in the return; not bounds-checking len.

Edge cases to handle

len==0 writes just {0,0} and returns 2; len==65535 is the maximum.

Background lessons

Up next

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