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");
    }


这样,就可以得到上传和下载的流量数据了。。。

 

程序运行结果:
 
 

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