libpcap編程--流量統計。。

從我的網易博客移動。。。


思路:對所抓的包進行分析。分析目標MAC地址和本機MAC地址的比較。如果一樣,則爲下載流量。否則是上傳流量

 

1,獲取本機MAC

設置一個全局變量

u_char uploadhost[ETHER_ADDR_LEN];
void getMac()//獲取本機MAC
{
    int sockfd;
  struct ifreq struReq;
  sockfd = socket(PF_INET,SOCK_STREAM,0);
  memset(&struReq,0,sizeof(struReq));
  strncpy(struReq.ifr_name, "eth0", sizeof(struReq.ifr_name));
  ioctl(sockfd,SIOCGIFHWADDR,&struReq);
  fprintf(stderr, "%d-%s\n", __LINE__, strerror(errno));
  printf("%s\n", ether_ntoa(struReq.ifr_hwaddr.sa_data));
  strcpy(uploadhost,ether_ntoa(struReq.ifr_hwaddr.sa_data));
  close(sockfd);
}


2,在pacp_loop的回調函數中進行包處理。。先將以太網報頭中的ether_dhost轉爲字符串。。

sprintf(dMac,"%x:%x:%x:%x:%x:%x",(eptr->ether_dhost)[0],(eptr->ether_dhost)[1],
            (eptr->ether_dhost)[2],(eptr->ether_dhost)[3],
            (eptr->ether_dhost)[4],(eptr->ether_dhost)[5]);


然後和uploadhost(本機MAC)進行比較確定這個是上傳還是下載數據包。並且統計數據。

if(strcmp(dMac,uploadhost) == 0)
    {
        dllen += pkthdr->len;//沒有去掉以太網,IP數據報的報頭長度,這樣流量統計略有誤差
    }
    else
    {
        uplen += pkthdr->len;
        printf("this is the upload!\n");
    }


這樣,就可以得到上傳和下載的流量數據了。。。

 

程序運行結果:
 
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章