'AF_PACKET socket receives many ethernet frames with mac address of 00:00:00:00:00:00

In the following packet sniffer in C, I set up the raw socket of AF_PACKET. And bind the socket to only one network device "eth0" with setsockopt system call. And get the packet from socket by recvfrom system call.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/if_ether.h>
#include <linux/filter.h>
#include <net/if.h>
#include <arpa/inet.h>

int main(int argc, char **argv) {
    int sock, n;
    char buffer[2048];
    unsigned char *iphead, *ethhead;

    if ((sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP))) < 0) {
        perror("socket");
        exit(1);
    }
    // bind to eth0 interface only
    const char *opt;
    opt = "eth0";
    if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, opt, strlen(opt) + 1) < 0) {
        perror("setsockopt");
        close(sock);
        exit(1);
    }

    while(1) {
        printf("-----------\n");
        n = recvfrom(sock, buffer, 2048, 0, NULL, NULL);
        printf("%d bytes read\n", n);

        /* Check to see if the packet contains at least
        * complete Ethernet (14), IP (20) and TCP/UDP
        * (8) headers.
        */
        if (n < 42) {
            perror("recvfrom():");
            printf("Incomplete packet (errno is %d)\n", errno);
            close(sock);
            exit(0);
        }

        ethhead = buffer;
        printf("Source MAC address: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
            ethhead[0], ethhead[1], ethhead[2], ethhead[3], ethhead[4], ethhead[5]
        );
        printf("Destination MAC address: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
            ethhead[6], ethhead[7], ethhead[8], ethhead[9], ethhead[10], ethhead[11]
        );

        iphead = buffer + 14; 

        if (*iphead==0x45) { /* Double check for IPv4
                            * and no options present */
            printf("Source host %d.%d.%d.%d\n",
                    iphead[12],iphead[13],
                    iphead[14],iphead[15]);
            printf("Dest host %d.%d.%d.%d\n",
                    iphead[16],iphead[17],
                    iphead[18],iphead[19]);
            printf("Source,Dest ports %d,%d\n",
                    (iphead[20]<<8)+iphead[21],
                    (iphead[22]<<8)+iphead[23]);
            printf("Layer-4 protocol %d\n",iphead[9]);
        }

    }
}

But it keeps printing ethernet frames as follows:

125 bytes read
Source MAC address: 00:00:00:00:00:00
Destination MAC address: 00:00:00:00:00:00
Source host 127.0.0.1
Dest host 127.0.0.1
Source,Dest ports 40830,38097
Layer-4 protocol 6

I was confused about what it is and where it comes from?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source