資料流的過濾
WinPcap或libpcap最強大的特點之一就是資料流的過濾引擎。它提供一種高效的方法來捕獲網路資料流的部分資料而且常常和WinPcap的捕獲機制相整合。過濾資料的函數是pcap_compile() 和 pcap_setfilter()。
pcap_compile()來編譯一個過濾裝置,它通過一個高層的boolean運算式產生一系列的能夠被過濾引擎所解釋的低層的位元組編碼。boolean表示文法能夠在開發包中找到。
pcap_setfilter() 用來聯絡一個在核心驅動上過濾的過濾器。一旦調用,這時所有網路資料包都將流經相關的過濾器,並拷貝到應用程式中。
下面的代碼展示了如何編譯並設定一個過濾器。注意我們必須從pcap_if結構中獲得掩碼(描述適配器),因為一些由pcap_compile()建立的過濾器在建立時需要這個參數。
下面的程式碼片段中pcap_compile()的"ip and tcp"參數說明只有既屬於IPV4又屬於TCP資料的包才會被傳遞到應用程式。
if (d->addresses != NULL)<br /> /* Retrieve the mask of the first address of the interface */<br /> netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;<br /> else<br /> /* If the interface is without an address we suppose to be in a C class network */<br /> netmask=0xffffff; </p><p>/*compile the filter*/<br /> if (pcap_compile(adhandle, &fcode, "ip and tcp", 1, netmask) < 0)<br /> {<br /> fprintf(stderr,"/nUnable to compile the packet filter. Check the syntax./n");<br /> /* Free the device list */<br /> pcap_freealldevs(alldevs);<br /> return -1;<br /> }</p><p>/*set the filter*/<br /> if (pcap_setfilter(adhandle, &fcode) < 0)<br /> {<br /> fprintf(stderr,"/nError setting the filter./n");<br /> /* Free the device list */<br /> pcap_freealldevs(alldevs);<br /> return -1;<br />}<br />
如何你想進一步查看本節中用過濾器過濾資料流的例子可以查看下一節——解析資料包。
附原文:
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