Read the packet before the protocol
Parse and validate IPv4 bytes in C, then inspect the same packet in the browser.
Jump to code and terminal ↓Packets are bytes with rules
A socket hides the network packet. Here the browser supplies deterministic IPv4 bytes in /work/packet.bin, and your C program interprets them in real Linux. The first packet carries a TCP SYN. The packet inspector displays its Ethernet wrapper, IPv4 header, and transport fields.
Validate before interpreting
IPv4's first byte combines a 4-bit version and a 4-bit header length. The header length counts 32-bit words, so 5 means 20 bytes. Reject the wrong version, a header shorter than 20 bytes, missing bytes, an impossible total length, and an invalid header checksum. Options make a valid header longer than 20 bytes.
byte 0 version (high 4 bits), IHL (low 4 bits) bytes 2–3 total length, big-endian byte 9 protocol: TCP = 6, UDP = 17 bytes 10–11 header checksum bytes 12–15 source IPv4 address bytes 16–19 destination IPv4 address
The output contract
On success, call the supplied print_header helper and return 0. ihl is measured in bytes. On invalid input, return nonzero; a diagnostic on stderr is welcome. Test sends different addresses, UDP, IPv4 options, truncated packets, and corrupt headers. The controlled link visualizer can introduce loss and delay; this first exercise reads captured packets rather than implementing a TCP peer.
version=4 ihl=20 total_length=40 protocol=6 src=10.0.0.1 dst=10.0.0.2
Your goal
Implement parse_ipv4: validate an IPv4 header and checksum, then print its length, protocol, and endpoint addresses.
What the tests observe
- Valid TCP and UDP packets parse
- IPv4 options change the header length
- Truncation and corrupt checksums are rejected
- The same bytes are visible in the inspector
Need a nudge?
Hint 1
Read p[0] only after checking size >= 20. version is p[0] >> 4 and header length in bytes is (p[0] & 15) * 4.
Hint 2
Use be16(p + 2) for total length. Require 20 <= header length <= total length <= the bytes available. Format addresses from four unsigned bytes.
Hint 3
For the IPv4 header checksum, add every big-endian 16-bit word in the whole header, including the checksum field. Fold carries back into the low 16 bits until none remain. A valid header sums to 0xffff.
What happens inside Linux
The C program reads the exact packet bytes generated by the controlled browser harness. It validates the IP envelope before interpreting the TCP or UDP payload. No Internet connection, server socket, or cloud machine participates. Later lessons will exchange frames with a deterministic peer and implement transport state.
Optional account sync. Exercises work without an account.