Search code examples
cnetwork-programmingethernet

Ethernet header from recvfrom is not as expected


I am writing some network packet sniffing code in C (running on an Ethernet LAN). While attempting to print out the Ethernet header, I've run into a bit of confusion. According to Wikipedia the first 8 bytes consist of the preamble and a delimiter and the next 6 are the MAC destination address.

However, when I actually run my code, I see that in the bytes I get from the recvfrom call, the initial 8 bytes (preamble and delimiter) are missing. In other words, I can start reading the destination address from the first byte itself.

Here is the relevant part of the code

char buffer[BUFFERSIZE];
struct addrinfo servinfo;

servinfo.ai_family = PF_PACKET;
servinfo.ai_socktype = SOCK_RAW;
servinfo.ai_protocol = htons(ETH_P_ALL);

int fd = socket(servinfo.ai_family, servinfo.ai_socktype, servinfo.ai_protocol);
int plen = recvfrom(fd, buffer, BUFFERSIZE, 0, &caddr, &clen);
int c = 0;
printf("Destination Address: %02x:%02x:%02x:%02x:%02x:%02x\n",buffer[c], buffer[c+1], buffer[c+2], buffer[c+3], buffer[c+4], buffer[c+5]);
printf("Source Address: %02x:%02x:%02x:%02x:%02x:%02x\n",buffer[c+6], buffer[c+7], buffer[c+8], buffer[c+9], buffer[c+10], buffer[c+11]);

This prints the correct destination address, whereas I should have gotten the correct result by printing after skipping the first 8 bytes in the buffer.

What am I missing here, or doing wrong?


Solution

  • This prints the correct destination address, whereas I should have gotten the correct result by printing after skipping the first 8 bytes in the buffer

    The preamble is a very low-level concept, handled strictly by the NIC. It's not even visible to the OS, let alone returned by recvfrom.