networking - Pcap丢弃数据包

标签 networking udp packet pcap libpcap

// Open the ethernet adapter
handle = pcap_open_live("eth0", 65356, 1, 0, errbuf);

// Make sure it opens correctly
if(handle == NULL)
{
    printf("Couldn't open device : %s\n", errbuf);
    exit(1);
}

// Compile filter
if(pcap_compile(handle, &bpf, "udp", 0, PCAP_NETMASK_UNKNOWN))
{
    printf("pcap_compile(): %s\n", pcap_geterr(handle));
    exit(1);
}

// Set Filter
if(pcap_setfilter(handle, &bpf) < 0)
{
    printf("pcap_setfilter(): %s\n", pcap_geterr(handle));
    exit(1);
}

// Set signals
signal(SIGINT, bailout);
signal(SIGTERM, bailout);
signal(SIGQUIT, bailout);

// Setup callback to process the packet
pcap_loop(handle, -1, process_packet, NULL);

process_packet 函数去掉了头部并对数据进行了一些处理。但是,当它花费太长时间时,我认为它正在丢弃数据包。

如何使用 pcap 监听 udp 数据包并能够在不丢失数据包的情况下对数据进行一些处理?

最佳答案

好吧,您没有无限的存储空间,因此,如果您持续运行的速度比数据包到达的速度慢,您将在某些时候丢失数据。
当然,如果您有足够的存储空间,并且平均而言,您不会落后(例如,您可能会在爆发期间跑得很慢,但在安静的时候可以 catch ),这将缓解问题。
一些网络嗅探器会这样做,只需将原始数据写入文件以供以后分析。
这是一个你也可以使用的技巧,虽然不一定与文件一起使用。可以使用大量内存结构,如循环缓冲区,其中一个线程(捕获线程)写入原始数据,另一个线程(分析)读取和解释。而且,因为每个线程只处理缓冲区的一端,您甚至可以在没有锁(或非常短的锁)的情况下构建它。
这也使您可以轻松检测是否已用完缓冲区并引发某种错误,而不仅仅是在应用程序级别丢失数据。
当然,这一切都取决于您的“尽可能简单和快速”的捕获线程能够跟上流量。

澄清我的意思,修改你的process_packet函数,以便它只将原始数据包写入一个巨大的循环缓冲区(检测溢出并采取相应措施)。这应该使它尽可能快,避免 pcap 本身丢弃数据包。
然后,有一个分析线程从队列中取出东西并完成以前在 process_packet 中完成的工作。 (“摆脱标题并对数据进行一些处理”位)。

另一种可能的解决方案是增加 pcap 内部缓冲区大小。根据手册页:

Packets that arrive for a capture are stored in a buffer, so that they do not have to be read by the application as soon as they arrive.

On some platforms, the buffer's size can be set; a size that's too small could mean that, if too many packets are being captured and the snapshot length doesn't limit the amount of data that's buffered, packets could be dropped if the buffer fills up before the application can read packets from it, while a size that's too large could use more non-pageable operating system memory than is necessary to prevent packets from being dropped.

The buffer size is set with pcap_set_buffer_size().



唯一想到的另一种可能性是确保您对每个数据包所做的处理尽可能优化。
将处理拆分为收集和分析应该可以缓解跟不上的问题,但它仍然依赖于安静的时间来追赶。如果您的网络流量始终超出您的分析所能处理的范围,那么您所做的就是拖延问题。优化分析可能是保证您永远不会丢失数据的唯一方法。

关于networking - Pcap丢弃数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501212/

相关文章:

c# - 为什么我的 UDP 数据包发送到我自己的公共(public) IP 时没有收到?

java - Netty 关闭/停止 UDP 服务器

java对等使用UDP套接字

https - 使用 SharpPCap 检测 HTTPS

c - ANSI C 中的外部/构建 TCP 数据包

ios - 具有多个快速连续请求的 AFHTTPSessionManager (AFNetworking 2.0)

networking - 如何连接两个 tcpdump 文件(pcap 文件)

azure - 来自 Google Cloud 的出站流量

c - UDP 客户端不会自动重新连接

tcp - OBD 模式 07 多帧