循序渐进学习使用WinPcap(一)

转载自安全焦点(翻译者yiedu),本文部分有修改。

一些需要知道的细节描述(前言):

      这一部分展示了如何使用WinPcap-API的不同的功能,它作为一个使用指南被划分为一系列的课时来带领读者循序渐进的体会Pcap的程序设计的魅力:从简单的基本功能(如获取网卡的列表,数据包的捕获等)到统计和收集网络流量等高级功能。

      这些例子是用C语言写的,所以在学习之前首先要有一定的C语言的基础,当然Pcap作为一个网络底层的驱动,要想学好它也必须具备一定的网络方面的知识。

最后说一下本机的环境:

      操作系统:Windows 7

      编程环境:Visual Studio 2010(关于编写WinPcap所需要的配置见上一篇日志)

      开发包版本:WinPcap 4.1.2

      得到网络驱动列表

      用WinPcap写应用程序的第一件事往往就是要获得本地的网卡列表。Libpcap和WinPcap都提供了pcap_findalldevs_ex()这个函数来实现此功能,这个API返回一个pcap_if结构的链表,链表的每项内容都含有全面的网卡信息:尤其是字段名字(name)和含有名字的描述(description)以及有关适配器(网卡)的信息。

下面这段程序取回适配器列表并且将它打印在屏幕上,如果没有适配器则打印错误:

有关这段程序的一些说明:

      首先,pcap_findalldevs_ex()同其他的libpcap函数一样有一个errbuf参数,当有异常情况发生时,这个参数会指向被libpcap填充为某个特定描述的错误字串。

      其次,请注意并非所有的系统都支持libpcap提供的网络程序接口。所以我们要想写出合适的程序就必须考虑到这些情况(系统不能够返回一些字段的描述信息),在这种情况下我门应该给出类似"No description available"这样的提示。

      最后,结束时别忘了用pcap_freealldevs()释放掉内存资源。

附原文(程序略):

Obtaining the device list

Typically, the first thing that a WinPcap-based application does is get a list of attached network adapters. Both libpcap and WinPcap provide the pcap_findalldevs_ex() function for this purpose: this function returns a linked list of pcap_if structures, each of which contains comprehensive information about an attached adapter. In particular, the fields name and description contain the name and a human readable description, respectively, of the corresponding device.

The following code retrieves the adapter list and shows it on the screen, printing an error if no adapters are found.

/* codes */

Some comments about this code.

First of all, pcap_findalldevs_ex(), like other libpcap functions, has an errbuf parameter. This parameter points to a string filled by libpcap with a description of the error if something goes wrong.

Second, remember that not all the OSes supported by libpcap provide a description of the network interfaces, therefore if we want to write a portable application, we must consider the case in which description is null: we print the string "No description available" in that situation.

Note finally that we free the list with pcap_freealldevs() once when we have finished with it.

#end

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值