WinPcap基础知识(第九课:统计网络的通信量)

这节课我们将要学习WinPcap的另外一个高级特性:对网络通信量进行统计。统计引擎使得内核级的包过滤器能有效的把收集到的包分类。你可以查阅NPF 驱动内部手册看到更多的细节。

 

 

为了用这个功能来监视网络,程序员必须要打开一个适配器,并且把它设为统计模式。可以用函数pcap_setmode()来完成这个功能。特别的,在这个函数里面MODE_STAT必须作为模式参数。

 

 

用统计模式,我们写一个监视TCP通信负载的应用程序,只需要很少行代码。下面是例子代码:

 

 

Before enabling statistical mode, the user has the option to set a filter that defines the subset of network traffic that will be monitored. See the paragraph on the Filtering expression syntax for details. If no filter has been set, all of the traffic will be monitored.

Once

 

the interface descriptor starts to work in statistical mode. Notice the fourth parameter (to_ms) of pcap_open(): it defines the interval among the statistical samples. The callback function receives the samples calculated by the driver every to_ms milliseconds. These samples are encapsulated in the second and third parameters of the callback function, as shown in the following figure:

 

 

Two 64-bit counters are provided: the number of packets and the amount of bytes received during the last interval.

In the example, the adapter is opened with a timeout of 1000 ms. This means that dispatcher_handler() is called once per second. At this point a filter that keeps only tcp packets is compiled and set. Then pcap_setmode() and pcap_loop() are called. Note that a struct timeval pointer is passed to pcap_loop() as the user parameter. This structure will be used to store a timestamp in order to calculate the interval between two samples. dispatcher_handler()uses this interval to obtain the bits per second and the packets per second and then prints these values on the screen.

Note finally that this example is by far more efficient than a program that captures the packets in the traditional way and calculates statistics at user-level. Statistical mode requires the minumum amount of data copies and context switches and therefore the CPU is optimized. Moreover, a very small amount of memory is required.

 

摘自:http://www.winpcap.org/docs/docs_41b5/html/group__wpcap__tut9.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值