<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->
WinPcap 导引:使用WinPcap 简明指导
WinPcap tutorial:a step by step guide to using WinPcap
翻译自WinPcap 开发包的帮助文档- 俞凌峰
第三篇: 打开网络适配器和捕获数据包
Opening an adapter and capturing the pcakets
Now that we've seen how to obtain an adapter to play with,let's start the real job,opening an adapter and capturing some traffic.In this lesson we'll write a program that prints some information about each packet flowing through the adapter.
到现在为止,我们已经知道了如何获得一个网络适配器,那就让我们开始真正的工作吧!开打一个网络适配器并捕获一些网络数据。在本章中,我们将会编写一个能打印通过一个特定网络适配器传输的网络数据包的某些信息的程序。
The function that opens a capture device is pcap_open().The parameters,snaplen,flags and to_ms deserve some explanation.
snaplen specifies the portion of the pcaket to capture.On some Oses(like xBSD and Win32),the packet driver can be configured to capture only the initial part of any packet:this decreases the amount of data to copy to the application and therefore improves the efficiency of the capture.In this case we use the value 65536 which is higher than the greatest MTU that we could encounter.In this manner we ensure that the application will always receive the whole packet.
flags: the most important flag is the one that indicates if the adapter will be put in promiscuous mode.In normal operation,an adapter only captures packets from the network that are destined to it;the pcakets exchanged by other hosts are therefore ignored.Instead,when the adapter is in promiscuous mode it captures all packets whether they are destined to it or not.This means that on shared media(like non-switched Ethernet),WinPcap will be able to capture the packets of other hosts.Promiscuous mode is the default for most capture applications,so we enable it in the following example.
to_ms specifies the read timeout,in millseconds.A read on the adapter(for example,with pcap_dispatch() or pcap_next_ex())will always return after to_ms millseconds,enen if no pcakets are available from the network.to_ms also defines the interval between statistical reports if the adapter is in statistical mode(see the lesson “/ref wpcap_tut9”for information about statistical mode).Setting to_ms to 0 means no timeout,a read on the adapter never returns if no packets arrive.A -1 timeout on the other side causes a read on the adapter to always return immediately.
打开一个捕获设备的函数是pcap_open() 。该函数参数是snaplen,flags,to_ms, 下面分别是各个参数的解释说明。
snaplen 指明了捕获数据包的哪一部分。在有些操作系统中(如xBSD 系统和Win32 系统),包捕获驱动可以配置成只捕获每个数据包的初始化部分:这能减少网络拷贝到应用程序中的数据从而提高了捕获的效率。在本例中我们设置该参数值为65536 ,这个参数值大大超过了链路层MTU (MTU 既最大传输单元,为某些链路的最大传输上限值) 。这样做