2

从 Linux 上的数据链路 (MAC) 层读取数据包的最简单/最短/最简单的方法是什么?

有人可以给我们一个关于如何做到这一点的代码片段吗?

为什么我们需要它?我们正在开发一种网络摄像机,其中千兆芯片仅实现数据链路层。由于我们没有资源来实现 IP 堆栈,因此我们只需要使用 MAC 地址来交换数据包。

4

1 回答 1

3

这是我正在寻找的代码片段:

#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;
}
于 2014-04-07T20:28:29.703 回答