【发布时间】:2022-01-01 06:30:39
【问题描述】:
我正在尝试通过原始套接字接收以太网数据包。 但行为并不像预期的那样。
代码在这里。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <net/ethernet.h>
#include <linux/if_packet.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/select.h>
int32_t main(int32_t argc, int8_t *argv[])
{
int32_t sock;
int8_t buf[1522];
int32_t ret;
int32_t bytes;
sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock == -1)
{
printf("socket open failed\n");
return 1;
}
ret = setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, "ens193", (strlen("ens193")+1));
if (ret == -1)
{
printf("interface binding failed\n");
close(sock);
return 1;
}
while(1)
{
bytes = recvfrom(sock, buf, 1522, 0, NULL, NULL);
if (bytes < 0)
{
printf("error in recvfrom\n");
exit;
}
printf("bytes = %d\n", bytes);
}
close(sock);
return 0;
}
并且执行输出在这里。
# ./a.out
[Nothing happening for a while]
bytes = 60
bytes = 42
bytes = 134
bytes = 118
bytes = 118
bytes = 118
bytes = 118
bytes = 118
bytes = 118
bytes = 66
...
...
...
但我认为接口实际上并没有收到任何数据包。 如果我看到 ifconfig 输出,则 RX 计数没有增加。 是因为我的代码中遗漏了一些东西吗? 如果你有什么好主意,请告诉我!
【问题讨论】:
-
您似乎正在捕获在指定接口上收到的所有流量,这可能并不总是计入 RX 计数。
-
你的意思是 ifconfig 不显示通过以太网驱动程序接收的所有数据包的计数吗?
-
既然你正在捕获
htons(ETH_P_ALL),那可能就是这种情况 -
为什么不用wireshark看看它们是什么?
-
我认为 htons(ETH_P_ALL) 意味着从设备/驱动程序接收所有以太网帧。 ifconfig 的 RX 计数应该与从设备/驱动程序接收到的以太网帧数匹配。
标签: c linux ethernet raw-sockets