質問

Which is the simplest/shortest/easiest way to read packets from data-link (MAC) layer on Linux?

Could someone give us a code snippet on how to do that?

Why do we need it? We are developing a network camera in which the gigabit chip implements only the data-link layer. Since we don't have resources to implement the IP stack, we need to exchange packets using only the MAC address.

役に立ちましたか?

解決

Here is the code snippet I was looking for:

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>


int main()
{
        int s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
        if (s == -1)
        {
            printf("Error while creating socket. Aborting...\n");
            return 1;
        }

        void* buffer = (void*)malloc(ETH_FRAME_LEN);
        while(1)
        {
            int receivedBytes = recvfrom(s, buffer, ETH_FRAME_LEN, 0, NULL, NULL);
            printf("%d bytes received\n", receivedBytes);
            int i;
            for (i = 0; i < receivedBytes; i++)
            {
               printf("%X ", ((unsigned char*)buffer)[i]);
            }
            printf("\n");
        }
        return 0;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top