其實代碼WpdPack裏都有,我要做的是在自己學習的基礎上寫下自己的理解,以及一些細節應該注意的問題。
使用winpcap編程,首先下載WpdPack,然後導入include和lib目錄,在工程中配置好wpcap.lib和Packet.lib,就可以使用winpcap進行編程了,具體方法網上很多,我就不羅嗦了。
這次要寫的是文檔的第一篇 獲取設備列表
首先要明白1個結構體的定義1個winpcap函數
pcap_f_t 這是一個保存設備名字和描述的結構體鏈表結構,有四個成員變量,
pcap_f *next 這是一個指向pcap_f結構的指針,其實就是鏈表中指向下一個元
素的next,而pcap_f結構和pcap_f_t其實是一個結構 typedef struct pcap_f pcap_f_t
char *name 這個指針指向你網絡適配器的名字
char *description 這個指針指向對網絡適配器的詳細描述
pcap_addr *address 看文檔貌似是指向鏈表第一個元素的地址,也就是說指向
鏈表中第一個網絡適配器的地址,這個本例中用不到,暫且不管
u_int flags 暫時用不到,不做解釋
pcap_findalldevs_ex函數,定義如下
int pcap_findalldevs_ex ( char * source //用來判斷是獲取本地還是遠程適配器,
struct pcap_rmtauth * auth, //本例用不到暫不做解釋
pcap_if_t ** alldevs, //把上面pcap_f_t的結構放進去來獲取網卡信息
char * errbuf //存放出錯信息
)
注意兩點 第一個參數char *source 如果賦值PCAP_SRC_IF_STRING則表示列出所有本地的適配器
還有第二個參數的定義是pcap_if_t ** ,注意要把第一個結構體指針的地址傳進去
在進行編程前還要注意一點,找到pcap.h文件,打開它,在#include <pcap/pcap.h>這句之前加上#define HAVE_REMOTE ,否則可能會報錯說上面的結構體和函數都沒有定義,看到網上有人說要加入#include "remote-ext.h" ,但其實加上以後會出現#error : Please do not include this file directly. Just define HAVE_REMOTE and then include pcap.h 意思是說不要包含這個頭文件,而要定義HAVE_REMOTE宏,所以按照我上面說的做就可以了。
好了,準備工作做好了,以下是代碼
#include "pcap.h"
#include "stdio.h"
#include "stdio.h"
int main(int argc,char *argv[])
{
pcap_if_t *alldevs; //define the list of the Network adapter device
pcap_if_t *d;
int i=0;
char errbuf[PCAP_ERRBUF_SIZE]; //PCAP_ERRBUF_SIZE is 256
/*Get the list of the device in loacal host*/
if(pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&alldevs,errbuf))
{
fprintf(stderr,"Error in pcap_findalldevs_ex",errbuf); /
exit(1);
}
{
pcap_if_t *alldevs; //define the list of the Network adapter device
pcap_if_t *d;
int i=0;
char errbuf[PCAP_ERRBUF_SIZE]; //PCAP_ERRBUF_SIZE is 256
/*Get the list of the device in loacal host*/
if(pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&alldevs,errbuf))
{
fprintf(stderr,"Error in pcap_findalldevs_ex",errbuf); /
exit(1);
}
/*show the list*/
for(d=alldevs;d;d=d->next)
{
printf("%d.%s\t",++i,d->name);
if(d->description)
{
printf("%s\n",d->description);
}
else
{
printf("No description available");
}
}
for(d=alldevs;d;d=d->next)
{
printf("%d.%s\t",++i,d->name);
if(d->description)
{
printf("%s\n",d->description);
}
else
{
printf("No description available");
}
}
if(i==0)
{
printf("No interface found!! Make sure Winpcap is installed\n");
return -1;
}
/*release the device*/
pcap_freealldevs(alldevs);
return 0;
}
{
printf("No interface found!! Make sure Winpcap is installed\n");
return -1;
}
/*release the device*/
pcap_freealldevs(alldevs);
return 0;
}
該程序在我的電腦上正確運行,編譯環境vc++6.0 ,運行結果應該是顯示出你所有的網卡設備。