WinPcap教程(一) 获取本地驱动设备列表

第一节:获取驱动列表

在这一节中讲述了,如何给予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.lib
3,代码最后记得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;
}


OK,Enjoy!

 

posted @ 2012-11-17 11:24  lianfei  阅读(2690)  评论(0编辑  收藏  举报
恋飞之家