循序渐进学习使用WINPCAP(五)

来源:互联网 发布:淘宝店铺能换支付宝吗 编辑:程序博客网 时间:2024/06/06 10:50

数据流的过滤

WinPcap或libpcap最强大的特点之一就是数据流的过滤引擎。它提供一种高效的方法来捕获网络数据流的部分数据而且常常和WinPcap的捕获机制相集成。过滤数据的函数是pcap_compile() 和 pcap_setfilter()。

pcap_compile()来编译一个过滤设备,它通过一个高层的boolean表达式产生一系列的能够被过滤引擎所解释的低层的字节编码。boolean表示语法能够在开发包中找到。

pcap_setfilter() 用来联系一个在内核驱动上过滤的过滤器。一旦调用,这时所有网络数据包都将流经相关的过滤器,并拷贝到应用程序中。

下面的代码展示了如何编译并设定一个过滤器。注意我们必须从pcap_if结构中获得掩码(描述适配器),因为一些由pcap_compile()创建的过滤器在创建时需要这个参数。

下面的代码段中pcap_compile()的"ip and tcp"参数说明只有既属于IPV4又属于TCP数据的包才会被传递到应用程序。

 

如何你想进一步查看本节中用过滤器过滤数据流的例子可以查看下一节——解析数据包。

附原文:

One of the most powerful features offered by WinPcap (and by libpcap as well) is the filtering engine. It provides a very efficient way to receive subsets of the network traffic, and is (usually) integrated with the capture mechanism provided by WinPcap. The functions used to filter packets are pcap_compile() and pcap_setfilter().

pcap_compile() takes a string containing a high-level Boolean (filter) expression and produces a low-level byte code that can be interpreted by the fileter engine in the packet driver. The syntax of the boolean expression can be found in the Filtering expression syntax section of this documentation.

pcap_setfilter() associates a filter with a capture session in the kernel driver. Once pcap_setfilter() is called, the associated filter will be applied to all the packets coming from the network, and all the conformant packets (i.e., packets for which the Boolean expression evaluates to true) will be actually copied to the application.

The following code shows how to compile and set a filter. Note that we must retrieve the netmask from the pcap_if structure that describes the adapter, because some filters created by pcap_compile() require it.

The filter passed to pcap_compile() in this code snippet is "ip and tcp", which means to "keep only the packets that are both IPv4 and TCP and deliver them to the application".

/* codes */

If you want to see some code that uses the filtering functions shown in this lesson, look at the example presented in the next Lesson, Interpreting the packets.

#end

原创粉丝点击