寫在前面:
參考
http://www.coffeecat.net.cn/winpcap,最近在接觸和熟悉WinpCap,并參考原來的代碼,改寫為VC6.0 環(huán)境的對話框工程,方便自己日后的使用,在此分享出來,希望能幫助一些需要熟悉WinpCap的朋友!
通常,編寫基于WinPcap應(yīng)用程序的第一件事情,就是獲得已連接的網(wǎng)絡(luò)適配器列表。libpcap和WinPcap都提供了
pcap_findalldevs_ex() 函數(shù)來實(shí)現(xiàn)這個功能: 這個函數(shù)返回一個
pcap_if 結(jié)構(gòu)的鏈表, 每個這樣的結(jié)構(gòu)都包含了一個適配器的詳細(xì)信息。值得注意的是,數(shù)據(jù)域
name 和
description 表示一個適配器名稱和一個可以讓人們理解的描述。
void CFindAllDevsDlg::OnBtnFindDevs()


{
// TODO: Add your control notification handler code here
int i=0;
char errBuf[PCAP_ERRBUF_SIZE];
CString strErr;
CString strDev;


/**//*獲取本機(jī)設(shè)備列表*/
if(pcap_findalldevs(&AllDevs,errBuf) == -1)

{
strErr.Format("Error in pcap_findalldevs_ex: %s",errBuf);
AfxMessageBox(strErr);
return;
}


/**//*打印列表*/
for(Dev=AllDevs; Dev!=NULL; Dev = Dev->next)

{
if(Dev->description)

{
//strDev.Format("%d.%s: %s",++i,Dev->name,Dev->description);
strDev.Format("%d",++i);
m_ctrlList.InsertItem((i-1),strDev);
strDev.Format("%s",Dev->name);
m_ctrlList.SetItemText((i-1),1,strDev);
strDev.Format("%s",Dev->description);
m_ctrlList.SetItemText((i-1),2,strDev);
}
else

{
strDev.Format("%d.%s: %s",++i,Dev->name,"No description available");
AfxMessageBox(strErr);
}
}
if(i == 0)

{
strErr = "No interfaces found! Make sure WinPcap is installed";
AfxMessageBox(strErr);
}

/**//*不再需要設(shè)備列表了,釋放它*/
pcap_freealldevs(AllDevs);

}

有關(guān)這段代碼的一些說明
首先, pcap_findalldevs() ,和其他libpcap函數(shù)一樣,有一個 errbuf 參數(shù)。一旦發(fā)生錯誤,這個參數(shù)將會被libpcap寫入字符串類型的錯誤信息。
第二要記住,不是所有的操作系統(tǒng)都支持libpcap提供的網(wǎng)絡(luò)程序接口,因此,如果我們想編寫一個可移植的應(yīng)用程序,我們就必須考慮在什么情況下, description 是 null。本程序中,我們遇到這種情況時(shí),會打印提示語句"No description available"。
最后要記住,當(dāng)我們完成了設(shè)備列表的使用,我們要調(diào)用 pcap_freealldevs() 函數(shù)將其占用的內(nèi)存資源釋放。
差別描述:源代碼使用
pcap_findalldevs_ex()獲取設(shè)備,但是在目前我配置的VC環(huán)境,提示找不到此函數(shù),所以使用
pcap_findalldevs()來實(shí)現(xiàn)??梢韵螺d工程代碼參考:/Files/Lee7/FindAllDevs.rar