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, minor), and length (2 bytes, big-endian). Implement
int tls_parse(const unsigned char *b, size_t n, int *type, int *major, int *minor, int *length)
returning 0 on success (writing the four fields), or -1 if n < 5. Parse from a fixed byte buffer — no network.
#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.