/*数据包捕获线程*/
UINT do_capture(LPVOID pParam)
{
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *fp;
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
CString str;
unsigned int i;
struct packetstru *cur_pack,*new_pack;
char s[100];
CStatic *static1,*static2;
int found;
static1=(CStatic *)AfxGetMainWnd()->GetDlgItem(IDC_STATIC1);
static2=(CStatic *)AfxGetMainWnd()->GetDlgItem(IDC_STATIC2);
fp = pcap_open_live(*devicename,65536,1,-1,errbuf); //打开网络设备
while(1)
{
if(captureflag==0)
break;
res = pcap_next_ex( fp, &header, &pkt_data); //读数据包
if(res==0) //超时返回
{
Sleep(1);
continue;
}
if(res<0) //发生错误
{
break;
}
if(res==1) //读数据包成功
{
//只捕获本网络设备发出或发给本网络设备的TCP包或UDP包
found=0;
if(pkt_data[0]==macaddress[0]&&pkt_data[1]==macaddress[1]&&
pkt_data[2]==macaddress[2]&&pkt_data[3]==macaddress[3]&&
pkt_data[4]==macaddress[4]&&pkt_data[5]==macaddress[5]||
pkt_data[6]==macaddress[0]&&pkt_data[7]==macaddress[1]&&
pkt_data[8]==macaddress[2]&&pkt_data[9]==macaddress[3]&&
pkt_data[10]==macaddress[4]&&pkt_data[11]==macaddress[5])
{
if(pkt_data[12]==0x08&&pkt_data[13]==0x00)
{
if(pkt_data[23]==0x06||pkt_data[23]==0x11)
found=1;
}
if(pkt_data[12]==0x88&&pkt_data[13]==0x64&&
pkt_data[20]==0x00&&pkt_data[21]==0x21)
{
if(pkt_data[31]==0x06||pkt_data[31]==0x11)
found=1;
}
}
if(found==1)
{
//目标MAC为本网卡MAC,则入包计数加1 if(macaddress[0]==pkt_data[0]&&macaddress[1]==pkt_data[1]&&
macaddress[2]==pkt_data[2]&&macaddress[3]==pkt_data[3]&&
macaddress[4]==pkt_data[4]&&macaddress[5]==pkt_data[5])
{
incount++;
}
//源MAC为本网卡MAC,则出包计数加1
if(macaddress[0]==pkt_data[6]&&macaddress[1]==pkt_data[7]&&
macaddress[2]==pkt_data[8]&&macaddress[3]==pkt_data[9]&&
macaddress[4]==pkt_data[10]&&macaddress[5]==pkt_data[11])
{
outcount++;
}
sprintf(s,"出包:%lu",outcount);
static1->SetWindowText(s);
sprintf(s,"入包:%lu",incount);
static2->SetWindowText(s);
//找到数据包链表的末尾
cur_pack=allpacket;
while(1)
{
if(cur_pack->next==NULL)
break;
cur_pack=cur_pack->next;
}
//为捕获到的数据包生成新节点,并加至数据包链表末尾
new_pack=new packetstru;
new_pack->datalen=header->len;
for(i=1;i<=header->len;i++)
new_pack->data[i-1]=pkt_data[i-1];
new_pack->clearflag=0;
new_pack->showflag=1;
new_pack->tick=GetTickCount();
new_pack->next=NULL;
cur_pack->next=new_pack;
}
}
}
pcap_close(fp); //关闭网络设备
return 0;
} |