Simvik

Read an Ethernet frame header

Decode MAC addresses and the EtherType, including a VLAN tag. A medium embedded C problem (I2S audio and Ethernet), run and graded in the browser.

medium · I2S audio and Ethernet · ethernet · networking · parsing

An Ethernet frame starts with the destination MAC (6 bytes), the source MAC (6 bytes) and a 2-byte EtherType (big-endian): 0x0800 for IPv4, 0x0806 for ARP, 0x86DD for IPv6.

If the EtherType is 0x8100, the frame carries a VLAN tag: the next 2 bytes hold the VLAN ID in their low 12 bits, and the real EtherType follows.

Write parse_eth(f, len, h): fill h and return the offset where the payload starts (14, or 18 with a VLAN tag), or -1 if the frame is too short for its header. Set vlan to -1 when there is no tag, and broadcast when the destination is FF:FF:FF:FF:FF:FF.

Starter code

int parse_eth(const uint8_t *f, int len, eth_t *h) {
  (void)len;
  memcpy(h->dst, f, 6);
  memcpy(h->src, f + 6, 6);
  h->type = (uint16_t)(f[12] | (f[13] << 8));
  h->vlan = -1;
  h->broadcast = false;
  return 14;
}

Example tests

An IPv4 frame

uint8_t f[20] = { 0x02,0x00,0x00,0x00,0x00,0x01, 0x02,0x00,0x00,0x00,0x00,0x02, 0x08,0x00 };
show(f, 20);

Expected output:

02:00:00:00:00:02 -> 02:00:00:00:00:01 type 0x0800 vlan -1 payload at 14

A broadcast ARP request

uint8_t f[20] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x80,0xE1,0x12,0x34,0x56, 0x08,0x06 };
show(f, 20);

Expected output:

00:80:E1:12:34:56 -> FF:FF:FF:FF:FF:FF (broadcast) type 0x0806 vlan -1 payload at 14

Learn it first