libpcap数据包嗅探流量分析

时间:2015-03-21 17:59:58

标签: c pcap

我在C ++上使用libpcap创建了一个数据包嗅探器。 我正在使用pcap_loop并调用一个loopback函数,目前我还没有想过。 这是我的代码。

int PacketSniff(int *count)
{
   int ifnum;
   int NumOfDevs=0;
   char errbuf[PCAP_ERRBUF_SIZE];
   bpf_u_int32 ip;
   bpf_u_int32  netmask;
   struct in_addr ip_addr , netmask_addr;
   pcap_if_t *devs , *d;
   pcap_t *handler;
   char packet_filter[] = "ip";
   struct bpf_program fcode;


   /* Find all interface devices */
   pcap_findalldevs(&devs, errbuf);

   for(d=devs; d; d=d->next)
   {
       printf("%d. %s", ++NumOfDevs, d->name);
       if (d->description)
       {
           printf(" (%s)\n", d->description);
       }
       else
       {
           printf(" (No description available)\n");
       }
   }
   if(NumOfDevs==0)
   {
       printf("\nNo interfaces found!\n");
       return (-1);
   }


   /* Prompt User to select interface */
   printf("Enter the interface number (1-%d):\n",NumOfDevs);
   scanf("%d",&ifnum);

   if(ifnum < 1 || ifnum > NumOfDevs)
   {
       printf("\nInterface number out of range.\n");
       /* Free the device list */
       pcap_freealldevs(devs);
       return (-1);
   }


   /* Jump to the selected adapter/interface */
   for(d=devs; ifnum>1 ;d=d->next, ifnum--);

   /* Open the selected adapter/interface */
   handler = pcap_open_live(d->name, 65535, 0, 2000, errbuf);

   if ((handler = pcap_open_live(d->name, 65535, 0, 2000, errbuf)) == NULL)
   {
       fprintf(stderr, "Couldn't open device %s: %s\n", d->name, errbuf);
       return(-1);
   }




   if (pcap_datalink(handler) != DLT_EN10MB )
   {
       fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
       pcap_freealldevs(devs);
       return -1;

   }

   /* This means that we set the datalink layer header size at 14 */
   int linkhdrlen = 14;


   if (pcap_lookupnet(d->name, &ip, &netmask, errbuf) <0 )
   {
       fprintf(stderr, "Can't get netmask for device %s\n", d->name);
       netmask = 0;
       ip = 0;
   }


   /* Compile the filter */
   if (pcap_compile(handler, &fcode, packet_filter, 1, netmask) <0 )
   {
       fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.  Error:  %s\n", errbuf);
       pcap_freealldevs(devs);
       return -1;
   }

   /* Set the filter */
   if (pcap_setfilter(handler, &fcode)<0)
   {
       fprintf(stderr,"\nError setting the filter. Error: %s\n", errbuf);
       pcap_freealldevs(devs);
       return -1;
   }


   printf("\nListening for packets on interface <%s>...\n", d->name);

   /* At this point, we don't need any more the device list. Free it */
   pcap_freealldevs(devs);

   pcap_loop(handler, 0, my_callback, NULL);}

而my_callback是这样的:

void my_callback(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_ptr){

   struct tm ltime;
   char timestr[16];
   struct ip_header *iphdr;
   struct tcp_header *tcphdr;
   time_t local_tv_sec;




   /* Convert the timestamp to readable format */

   local_tv_sec = header->ts.tv_sec;
   localtime_r(&local_tv_sec , &ltime);
   strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);

   /* Print timestamp and length of the packet */
   printf("Time >> %s.%.6d \nPacket Length:%d \n\n", timestr, header->ts.tv_usec, header->len);

   /* Retireve the position of the ip header    http://www.tcpdump.org/pcap.html */
   iphdr = (ip_header *) (pkt_ptr +14);       




   // Advance to the transport layer header then parse and display
   // the fields based on the type of hearder: tcp, udp or icmp.

   pkt_ptr += 4*iphdr->ver_ihl ;
   tcphdr = (tcp_header *)(pkt_ptr + 14);
   /* print ip addresses and tcp ports */
   printf("%d.%d.%d.%d : %d ---> %d.%d.%d.%d : %d\n\n",
          iphdr->saddr.byte1,
          iphdr->saddr.byte2,
          iphdr->saddr.byte3,
          iphdr->saddr.byte4,
          tcphdr->src_port,
          iphdr->daddr.byte1,
          iphdr->daddr.byte2,
          iphdr->daddr.byte3,
          iphdr->daddr.byte4,
          tcphdr->dst_port);}

现在我可以嗅闻数据包并打印各种东西。 但我的目标是从数据包中提取统计数据(如numOfpackets,numOfTCPpackets,numOfIncomingPAcket,numOfOutgoingPackets,Packet Size Variance,Time Interval Variance),同时它们被嗅探。 但我希望这能在1000毫秒时间窗口完成。

例如:每1000毫秒我想要一个输出文件..

numOfTCPPackets = ....

numof = ....

我的问题是: 我如何整合那些Time-Windows? 如何提取所需的统计数据而不会过多地干扰嗅探速度。?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

使用pcap_next()而不是pcap_loop()来获取数据包,并将pcap_set_timeout()的超时设置为一个较小的值,例如10毫秒,以防止pcap_next()永远阻塞,以便您的代码将统计信息写入文件有机会跑。您需要在循环中调用pcap_next()并在pcap_next()调用之后使用以下代码:

if (cur_time64() - last_time64 >= stat_time64)
{
    last_time64 += stat_time64;
    print_statistics_to_file();
}

...其中cur_time64()将当前时间作为64位整数(自纪元以来以微秒为单位)返回(如果使用类Unix操作系统,可以使用gettimeofday()实现cur_time64())。在您的示例中,stat_time64将为1秒,即1000 * 1000。

然后,继续处理数据包。检查pcap_next()的返回值,看它是否返回了一个数据包:如果没有,继续循环;如果是,请处理该数据包。

要在不过多干扰嗅探速度的情况下进行检查,您唯一的选择是尽可能高效地编写代码。只处理那些你绝对需要处理的头字段,即你可以避免检查IP和TCP头的校验和。