networking · intermediate · ~20 min
Parse a fixed binary protocol header with a big-endian length field.
A TLS record begins with a 5-byte header: content type (1 byte), protocol version (2 bytes — major then minor), and a record length (2 bytes, big-endian). Parse those four fields out of a fixed byte buffer. No network involved.
Implement int tls_parse(const unsigned char *b, size_t n, int *type, int *major, int *minor, int *length) that reads the header from b and writes the four fields.
Layout: type = b[0], major = b[1], minor = b[2], length = (b[3] << 8) | b[4] (big-endian).
b, n: the record bytes and how many are available.type, major, minor, length: out-pointers for the four fields.Returns 0 on success (all four fields written), or -1 if fewer than 5 bytes are available (n < 5).
{0x16,0x03,0x03,0x00,0x2f} -> 0, type=22, major=3, minor=3, length=47
{0x17,0x03,0x03,0x01,0x00} -> 0, type=23, length=256
n = 4 -> -1
-1 without writing the outputs.Record bytes (b) and available length (n), plus out-pointers type, major, minor, length.
Returns 0 with the four fields written, or -1 if n < 5.
Require at least 5 bytes; read the length field as big-endian (b[3] high byte, b[4] low byte).
#include <stddef.h>
int tls_parse(const unsigned char *b, size_t n,
int *type, int *major, int *minor, int *length) {
/* TODO: need at least 5 bytes. type=b[0], version=b[1].b[2],
length = big-endian b[3..4]. Return 0, or -1 if too short. */
(void)b;(void)n;(void)type;(void)major;(void)minor;(void)length;
return -1;
}
Reading before the length check; little-endian length; sign-extending bytes.
Exactly 5 bytes (minimum). Length 0x0100 = 256. Buffer shorter than 5.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.