if(InitAdapter())
{
int nIndex = m_ctrlComboType.GetCurSel();
_beginthreadex(NULL,0,&CaptureFunc,(LPVOID)nIndex,0,&m_thread_id);//启动线程
}
else
{
AfxMessageBox("Init Adapter Error!");
}//初始化网络适配器
bool CWinpCapDemoDlg::InitAdapter()
{
char errBuf[PCAP_ERRBUF_SIZE];
int i;
//寻找网络适配器
if(pcap_findalldevs(&allDevs,errBuf) == -1)
{
AfxMessageBox("Error in pcap_findalldevs");
return false;
} for(Dev = allDevs,i=0;i<0;Dev = Dev->next,i++);
//打开选取的网络适配器
if((adHandle = pcap_open_live(Dev->name,65535,1,20,errBuf)) == NULL)
{
AfxMessageBox("Unable to open the adapter!");
pcap_freealldevs(allDevs);
return false;
}
//判断网络是否为10MB以太网
if(pcap_datalink(adHandle) != DLT_EN10MB)
{
AfxMessageBox("This program works only on Ethernet network!");
pcap_freealldevs(allDevs);
return false;
}
return true;}unsigned int WINAPI CWinpCapDemoDlg::CaptureFunc(LPVOID param)
{
int count = 0;
int* nIndex = (int *)param;
CString strIndex;
strIndex.Format("%d",nIndex);
int nType = atoi(strIndex);
//AfxMessageBox(strIndex);
while(count <= 5)
{
//捕获数据报
pcap_loop(adHandle,1,ETH_Dispatcher_Handler,NULL);//参数3必须为一个回调函数
}
return 1;
} void ETH_Dispatcher_Handler(u_char *, const pcap_pkthdr* header, const u_char *p)
{
PETHHEADER eth = (PETHHEADER)p;
CWinpCapDemoDlg dlg = new CWinpCapDemoDlg; CString strShost,strDhost,strType;
strShost.Format("%02X",eth->ether_shost);
strDhost.Format("%02X",eth->ether_dhost);
strType.Format("%02X",htons(eth->ether_type));
}
{
int nIndex = m_ctrlComboType.GetCurSel();
_beginthreadex(NULL,0,&CaptureFunc,(LPVOID)nIndex,0,&m_thread_id);//启动线程
}
else
{
AfxMessageBox("Init Adapter Error!");
}//初始化网络适配器
bool CWinpCapDemoDlg::InitAdapter()
{
char errBuf[PCAP_ERRBUF_SIZE];
int i;
//寻找网络适配器
if(pcap_findalldevs(&allDevs,errBuf) == -1)
{
AfxMessageBox("Error in pcap_findalldevs");
return false;
} for(Dev = allDevs,i=0;i<0;Dev = Dev->next,i++);
//打开选取的网络适配器
if((adHandle = pcap_open_live(Dev->name,65535,1,20,errBuf)) == NULL)
{
AfxMessageBox("Unable to open the adapter!");
pcap_freealldevs(allDevs);
return false;
}
//判断网络是否为10MB以太网
if(pcap_datalink(adHandle) != DLT_EN10MB)
{
AfxMessageBox("This program works only on Ethernet network!");
pcap_freealldevs(allDevs);
return false;
}
return true;}unsigned int WINAPI CWinpCapDemoDlg::CaptureFunc(LPVOID param)
{
int count = 0;
int* nIndex = (int *)param;
CString strIndex;
strIndex.Format("%d",nIndex);
int nType = atoi(strIndex);
//AfxMessageBox(strIndex);
while(count <= 5)
{
//捕获数据报
pcap_loop(adHandle,1,ETH_Dispatcher_Handler,NULL);//参数3必须为一个回调函数
}
return 1;
} void ETH_Dispatcher_Handler(u_char *, const pcap_pkthdr* header, const u_char *p)
{
PETHHEADER eth = (PETHHEADER)p;
CWinpCapDemoDlg dlg = new CWinpCapDemoDlg; CString strShost,strDhost,strType;
strShost.Format("%02X",eth->ether_shost);
strDhost.Format("%02X",eth->ether_dhost);
strType.Format("%02X",htons(eth->ether_type));
}
如果需要检查捕捉的报文可以在回调函数ETH_Dispatcher_Handler中处理
最近在学习pcap,今天同样也遇到这个问题,后来查了pcap的manpage,发现pcap_loop()是阻塞工作方式的,当没有包捕获时,程序就阻塞在这一行了,和阻塞式的socket类似。