Parse Ethernet, IP and TCP Headers in C
Read raw frames with an AF_PACKET socket and parse Ethernet, IPv4 and TCP headers in C using the Linux header structs, with length checks at every layer.

Every packet on a network is a stack of headers laid end to end: an Ethernet header, then an IP header, then a TCP header, then your data. Parsing them is the best way to learn what these protocols actually carry, and the C needed is short. This post builds a small program that receives raw frames on Linux and prints the addresses, ports and flags it finds. It uses C17, glibc 2.40 and Linux 6.12, and its only prerequisite is the idea of a struct. If byte order is new to you, read the post on network byte order first, because every multi-byte field here arrives in it.
What a frame looks like
A TCP segment inside IPv4 inside Ethernet is laid out like this, with every number a byte count:
| Layer | Starts at byte | Fixed size | Fields you will read |
|---|---|---|---|
| Ethernet | 0 | 14 | destination MAC, source MAC, EtherType |
| IPv4 | 14 | 20 to 60 | header length, protocol, source and destination address |
| TCP | 14 plus IP header length | 20 to 60 | ports, sequence number, flags |
The IPv4 header length is not fixed, because the header may carry options. Its low nibble, the IHL field, counts the header in 32-bit words, so a plain header has IHL 5, which is 20 bytes. The TCP header has the same trick: a data-offset field in 32-bit words. You must read both fields to find where the next layer begins. Hard-coding 20 works until the first packet with options, and then you read the wrong bytes.
Linux ships ready-made structs for these headers. <linux/if_ether.h> provides struct ethhdr, <netinet/ip.h> provides struct iphdr (with glibc, also available as struct ip), and <netinet/tcp.h> provides struct tcphdr. The glibc tcphdr uses the field names source, dest, seq, doff and th_flags, with bit-field members for the flags depending on __USE_MISC. This post uses the th_flags byte and the TH_SYN-style macros, which are the portable spelling.
Open a raw socket
A packet socket delivers whole frames. Creating one needs CAP_NET_RAW, as documented in packet(7), so run the program with sudo or grant the capability to the binary.
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
static void print_mac(const char *label, const uint8_t *m)
{
printf("%s %02x:%02x:%02x:%02x:%02x:%02x", label,
m[0], m[1], m[2], m[3], m[4], m[5]);
}
static void parse(const uint8_t *buf, size_t len);
int main(void)
{
int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
if (fd < 0) {
perror("socket");
return 1;
}
uint8_t buf[65536];
for (int i = 0; i < 4; i++) {
ssize_t n = recv(fd, buf, sizeof buf, 0);
if (n < 0) {
perror("recv");
break;
}
parse(buf, (size_t)n);
}
close(fd);
return 0;
}Passing htons(ETH_P_IP) as the protocol asks the kernel to deliver only IPv4 frames, so you do not have to filter ARP and IPv6 yourself. The argument is in network byte order, which is the usual trap with packet sockets: ETH_P_IP alone matches nothing useful on a little-endian machine.
Parse layer by layer, checking length first
The rule for every parser is to check that the bytes exist before reading them. A short frame must produce a return, not a read past the buffer. Each layer checks its own minimum, then reads the length field to find the next layer, then checks that the length field itself is sane.
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
void parse(const uint8_t *buf, size_t len)
{
if (len < sizeof(struct ethhdr))
return;
struct ethhdr eth;
memcpy(ð, buf, sizeof eth);
if (ntohs(eth.h_proto) != ETH_P_IP)
return;
const uint8_t *ip_start = buf + sizeof eth;
size_t ip_avail = len - sizeof eth;
if (ip_avail < sizeof(struct iphdr))
return;
struct iphdr ip;
memcpy(&ip, ip_start, sizeof ip);
size_t ip_len = (size_t)ip.ihl * 4;
if (ip.version != 4 || ip_len < sizeof ip || ip_len > ip_avail)
return;
if (ip.protocol != IPPROTO_TCP)
return;
const uint8_t *tcp_start = ip_start + ip_len;
size_t tcp_avail = ip_avail - ip_len;
if (tcp_avail < sizeof(struct tcphdr))
return;
struct tcphdr tcp;
memcpy(&tcp, tcp_start, sizeof tcp);
size_t tcp_len = (size_t)tcp.doff * 4;
if (tcp_len < sizeof tcp || tcp_len > tcp_avail)
return;
char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip.saddr, src, sizeof src);
inet_ntop(AF_INET, &ip.daddr, dst, sizeof dst);
printf("%s:%u -> %s:%u flags=0x%02x payload=%zu\n",
src, ntohs(tcp.source), dst, ntohs(tcp.dest),
tcp.th_flags, tcp_avail - tcp_len);
}Each memcpy copies the header into a local struct, which avoids unaligned access and aliasing problems. The IPv4 header sits at offset 14, so a 4-byte field inside it is not guaranteed to be aligned for direct access on every architecture. Copying is cheap and removes the question.
Notice what each check protects against. ip_len > ip_avail catches a header length field that claims more bytes than the frame holds, which is exactly what a malformed or hostile packet looks like. tcp_len < sizeof tcp catches a data offset below five words, a value no real stack sends. Without these two lines the code would compute a payload size that wraps around to a huge unsigned number.
inet_ntop converts a binary address to text and takes it in network order, so you pass &ip.saddr directly with no ntohl. The ports are 16-bit fields and need ntohs. The flags are one byte and need nothing.
A session against a host that is opening a connection prints something like this. Addresses and ports will differ:
192.0.2.10:51322 -> 198.51.100.7:443 flags=0x02 payload=0
198.51.100.7:443 -> 192.0.2.10:51322 flags=0x12 payload=0
192.0.2.10:51322 -> 198.51.100.7:443 flags=0x10 payload=0
192.0.2.10:51322 -> 198.51.100.7:443 flags=0x18 payload=517Read the flags as bits. 0x02 is SYN, 0x12 is SYN plus ACK (0x02 | 0x10), 0x10 is a bare ACK, and 0x18 is PSH plus ACK, the first data segment. This is the three-way handshake from RFC 9293, and seeing it as bytes in your own program makes the diagram in the textbook concrete.
Why the checks come in this order
The order of the checks is not arbitrary, and it is worth seeing why. Each layer's length field is only meaningful once you know the bytes holding it exist, so the existence check always comes first. Then the length field is validated against both a lower bound (the fixed minimum for that header) and an upper bound (what the frame still holds). Only after both pass is it safe to use the field to compute where the next layer begins. Swap any two steps and you either read uninitialised bytes or compute an offset from a garbage value.
A practical habit follows from this: write the parser so that each layer is a function that takes a pointer and a remaining length and returns either the next pointer and its remaining length or a failure. That shape makes the invariant, "never read past end", something you can see on one screen instead of reasoning about across a long function. It also gives you a natural place to count why packets were rejected, which is the first thing you want when a capture looks emptier than expected.
Another point is worth stating plainly. The Ethernet header on a capture does not include the 4-byte frame check sequence at the end, because the NIC strips and verifies it before the kernel sees the frame. If you compare byte counts with a hardware tap you will see four more bytes on the wire than in your buffer. Padding is different: short frames are padded to a 60-byte minimum before the checksum, and that padding does reach you, which is why the IP total-length field, not the buffer length, tells you where the datagram really ends.
Decode the flags
Printing a hex byte is fine for debugging, but a small helper makes the output readable. The glibc header defines TH_FIN, TH_SYN, TH_RST, TH_PUSH, TH_ACK and TH_URG as masks, under _DEFAULT_SOURCE, which is on by default with GCC.
#include <netinet/tcp.h>
#include <stdint.h>
#include <stdio.h>
static void flag_names(uint8_t f, char out[16])
{
char *p = out;
if (f & TH_SYN) *p++ = 'S';
if (f & TH_FIN) *p++ = 'F';
if (f & TH_RST) *p++ = 'R';
if (f & TH_PUSH) *p++ = 'P';
if (f & TH_ACK) *p++ = '.';
if (p == out) *p++ = '-';
*p = '\0';
}
int main(void)
{
uint8_t samples[] = { 0x02, 0x12, 0x10, 0x18, 0x11, 0x04 };
char names[16];
for (size_t i = 0; i < sizeof samples; i++) {
flag_names(samples[i], names);
printf("0x%02x -> %s\n", samples[i], names);
}
return 0;
}0x02 -> S
0x12 -> S.
0x10 -> .
0x18 -> P.
0x11 -> F.
0x04 -> RThe dot for ACK follows the notation tcpdump prints, so output from your program lines up with what you see in a capture. Each letter is one bit, so combinations such as FIN plus ACK read as F..
Run it safely
Grant the capability instead of running as root:
gcc -std=c17 -Wall -Wextra -o sniff sniff.c parse.c
sudo setcap cap_net_raw=eip ./sniff
./sniffWithout the capability, socket fails and the program prints the error from perror:
socket: Operation not permittedWhat this parser does not handle
It reads only IPv4 over Ethernet with no VLAN tag. A frame with a VLAN tag has EtherType 0x8100, and the real type sits four bytes later, so it is skipped here. IPv6 has a different header and a chain of extension headers, so it needs its own function. IP fragments after the first have no TCP header at all, and the code above would misread their payload as one. A real tool checks the fragment-offset field and skips them. Finally, it trusts that the NIC delivered a complete frame. With receive offloads on, a capture may contain a segment larger than the MTU, so a length that looks impossible on the wire can be normal on the capture side.

