如何刷新原始AF_PACKET套接字以获取正确的已过滤数据包 [英] How to flush raw AF_PACKET socket to get correct filtered packets

查看:69
本文介绍了如何刷新原始AF_PACKET套接字以获取正确的已过滤数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &f, sizeof (f)) 

使用这个简单的BPF/LPF附加代码,当我尝试在套接字上接收数据包时,将得到一些与过滤器不匹配的错误数据包.似乎那些数据包在我调用setsockopt()之前就已经进入套接字了.

With this simple BPF/LPF attach code, when I try to receive packet on the socket, will get some wrong packets that doesn't match with the filter. Seems those packets got into the socket before I call setsockopt().

好像应该先创建AF_PACKET SOCK_RAW套接字,然后附加过滤器,然后冲洗套接字以清除那些错误的数据包.

Seems like should first create the AF_PACKET SOCK_RAW socket, then attach the filter, then flush the socket to get rid of those wrong packets.

问题是,如何清除那些数据包?

So the question is, how to flush those packet?

推荐答案

"bug"您所描述的是真实的,而且我在职业生涯中的多家公司中都看到过它.存在类似于口头传统"的东西.解决此错误是由一位网络工程师传给另一位工程师的.以下是常见的修补程序:

The "bug" you're describing is real and I've seen it at multiple companies in my career. There is something like an "oral tradition" around this bug that is passed from one network engineer to another. Here are the common fixes:

  1. 只需在套接字上调用 recv ,直到它为空
  2. 通过在用户模式下以及使用bpf过滤数据包进行双重过滤
  3. 像libpcap一样使用零bpf技术,在这种情况下,您首先应用一个空的bpf,然后清空套接字,然后应用真实的bpf.

我已经在我的博客上广泛讨论了这个问题尝试将围绕此错误的口头惯例整理成具体的建议和最佳实践.

I've written about this problem extensively on my blog to try and codify the oral tradition around this bug into a concrete recommendation and best-practice.

这篇关于如何刷新原始AF_PACKET套接字以获取正确的已过滤数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆