WinPcap. 获取本地驱动设备列表

来源:互联网 发布:jsp音乐网站源码 编辑:程序博客网 时间:2024/05/19 13:58

第一节:获取驱动列表

在这一节中讲述了,如何给予WinPcap获取网络适配器列表。主要通过函数pcap_findalldevs_ex(),它返回一个pcap_if结构的链表,每一个pcap_if结构保存一个适配器的信息,遍历输出所有的适配器信息后,要记得调用pcap_freealldevs()函数释放。

首先看一下pcap_findalldevs_ex()函数原型: 

复制代码
int pcap_findalldevs_ex (    char *  source,     struct pcap_rmtauth *  auth,     pcap_if_t **   alldevs,    char *  errbuf)
复制代码

 

该函数是pcap_findalldevs()的扩展形式,它只列出本地机器的驱动设备。

复制代码
 1 参数说明: 2  3 Char * source ;  适配器文件所在位置,取值有: 4  5 (1), 'rpcap://'   表示本地的适配器,此时可以用宏定义PCAP_SRC_IF_STRING。 6  7 (2), ’rpcap://hostname:prot’  表示主机名称为hostname并且端口号为port,如本地的hostname为”localhost”,端口号一般为”80”. 8  9 (3),  'file://c:/myfolder/', 指定路径。10 11    Struct  pcap_rmtauth * auth; 指向pcap_rmtauth结构体,当连接到远程host时,需要它保存一些信息。对于本地连接时没有意义,一般去NULL。12 13 Pcap_if_t ** alldevs; 利用结构体pcap_if存储适配器信息,并保存在链表结构的alldevs中。14 15 Char * errbuf; 保存错误信息。16 17 返回为0成功,否则返回-1,失败信息保存在errbuf中。
复制代码

 

Pcap_if结构:                  

复制代码
 1 变量说明: 2  3    Struct  pcap_if * next; 指向下一个结构体。 4  5     Char * name; 指向该适配器名称。 6  7     Char * description; 适配器描述内容。 8  9     Struct pcap_addr * address;10 11       U_int flags;
复制代码

 

复制代码
/********************************************** 代码贡献:* 注意事项:    1,第一行加上“#define HAVE_REMOTE”,这样就不要加上头文件 remote-ext.h,也就是说两者效果一样,但推荐前者。2,很多教程中都只是添加头文件”pcap.h” 会提示相关函数无法解析,需要添加依赖库wpcap.lib3,代码最后记得pcap_freealldevs()。*********************************************/#define HAVE_REMOTE#include "pcap.h"#pragma comment(lib,"wpcap.lib")int main(){    pcap_if_t *alldevs;    pcap_if_t *d;    int i = 0;    char errbuf[PCAP_ERRBUF_SIZE];    /*    get local devices     */    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&alldevs,errbuf) == -1)    {        fprintf(stderr,"Error in pcap_findalldevs_ex:%s\n",errbuf);        exit(1);    }    /* print devices 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 avaliable)\n");    }    if (i == 0)    {        printf("\nNo interfaces found! Make sure Winpcap is installed.\n");        return -1;    }    pcap_freealldevs(alldevs);    system("pause");    return 0;}
复制代码
0 0