第一步:下载安装winPcap(软件+开发包)
下载地址:http://download.youkuaiyun.com/source/1822448,也可以在官方网站下载(注意是软件+开发包哦)。
第二步:导入winPcap开发包
打开VC6.0,依次点击 “工具”—>“选择”—>“目录”,在“路径”下导入解压后的开发包中Include文件夹的目录,例如:D:/WINPCAP_4_0_2/WPDPACK/INCLUDE,点击“确定”。
第三步: 新建C++ Source file文件
程序代码如下:
- #include "pcap.h"
- #include "remote-ext.h"
- main()
- {
- pcap_if_t *alldevs;
- pcap_if_t *d;
- int i=0;
- char errbuf[PCAP_ERRBUF_SIZE];
- /* Retrieve the device list from the local machine */
- if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1)
- {
- fprintf(stderr,"Error in pcap_findalldevs_ex: %s/n", errbuf);
- exit(1);
- }
- /* Print the list */
- for(d= alldevs; d != NULL; d= d->next)
- {
- printf("%d. %s", ++i, d->name);
- if (d->description)
- printf(" (%s)/n", d->description);
- else
- printf(" (No description available)/n");
- }
- if (i == 0)
- {
- printf("/nNo interfaces found! Make sure WinPcap is installed./n");
- return;
- }
- /* We don't need any more the device list. Free it */
- pcap_freealldevs(alldevs);
- }
上面代码的一些说明:
首先,pcap_findalldevs_ex()函数,和别的libpcap函数一样,有一个errbuf参数。如果出了错误,这个参数指向一个由libpcap填充的关于错误信息的字符串。
其次,记住并非所有libpcap支持的操作系统都会提供网卡描述信息,因此,如果我们想编写可移植的程序,就必须考虑到描述信息为空的情况,在上面的程序中,我们输出“No description available”。
最后,注意一旦我们处理完毕,要调用pcap_freealldevs()来释放相关资源。
第四步:添加wpcap.lib文件
把解压后的开发包中的wpcap.lib文件拷到新建的C++ Source file同级目录中,然后依次点击“工程”—>“设置”—>“Link”,在“对象/库模块”下文本框的未尾输入" wpcap.lib",注意 wpcap.lib前面有空格,然后点击“确定”。
第五步:编译和运行这个程序
编译后运行它。得到类似如下的结果(译注:不同的机器上得到结果有所不同):
1. /Device/NPF_{4E273621-5161-46C8-895A-48D0E52A0B83} (Realtek RTL8029(AS) Ethernet Adapter)
2. /Device/NPF_{5D24AE04-C486-4A96-83FB-8B5EC6C7F430} (3Com EtherLink PCI)
在我的机器上运行后效果图:
如果你能看到类似的结果就OK啦!