WinPcap编程【6】过滤、分析数据包

WinPcap和Libpcap的最强大的特性之一,是拥有过滤数据包的引擎。 它提供了有效的方法去获取网络中的某些数据包,这也是WinPcap捕获机制中的一个组成部分。 用来过滤数据包的函数是 pcap_compile() 和pcap_setfilter() 。

pcap_compile() 它将一个高层的布尔过滤表达式编译成一个能够被过滤引擎所解释的低层的字节码。有关布尔过滤表达式的语法可以参见 Filtering expression syntax 这一节的内容。

pcap_setfilter() 将一个过滤器与内核捕获会话向关联。当 pcap_setfilter() 被调用时,这个过滤器将被应用到来自网络的所有数据包,并且,所有的符合要求的数据包 (即那些经过过滤器以后,布尔表达式为真的包) ,将会立即复制给应用程序。

现在,我们可以捕捉并过滤网络流量了,那就让我们学以致用,来做一个简单使用的程序吧。

在本讲中,我们将会利用上一讲的一些代码,来建立一个更实用的程序。 本程序的主要目标是展示如何解析所捕获的数据包的协议首部。这个程序可以称为UDPdump,打印一些网络上传输的UDP数据的信息。

我们选择分析和现实UDP协议而不是TCP等其它协议,是因为它比其它的协议更简单,作为一个入门程序范例,是很不错的选择。让我们看看代码:

[cpp]  view plain copy
  1. #include "pcap.h"  
  2.   
  3. /* 4字节的IP地址 */  
  4. typedef struct ip_address{  
  5.     u_char byte1;  
  6.     u_char byte2;  
  7.     u_char byte3;  
  8.     u_char byte4;  
  9. }ip_address;  
  10.   
  11. /* IPv4 首部 */  
  12. typedef struct ip_header{  
  13.     u_char  ver_ihl;        // 版本 (4 bits) + 首部长度 (4 bits)  
  14.     u_char  tos;            // 服务类型(Type of service)   
  15.     u_short tlen;           // 总长(Total length)   
  16.     u_short identification; // 标识(Identification)  
  17.     u_short flags_fo;       // 标志位(Flags) (3 bits) + 段偏移量(Fragment offset) (13 bits)  
  18.     u_char  ttl;            // 存活时间(Time to live)  
  19.     u_char  proto;          // 协议(Protocol)  
  20.     u_short crc;            // 首部校验和(Header checksum)  
  21.     ip_address  saddr;      // 源地址(Source address)  
  22.     ip_address  daddr;      // 目的地址(Destination address)  
  23.     u_int   op_pad;         // 选项与填充(Option + Padding)  
  24. }ip_header;  
  25.   
  26. /* UDP 首部*/  
  27. typedef struct udp_header{  
  28.     u_short sport;          // 源端口(Source port)  
  29.     u_short dport;          // 目的端口(Destination port)  
  30.     u_short len;            // UDP数据包长度(Datagram length)  
  31.     u_short crc;            // 校验和(Checksum)  
  32. }udp_header;  
  33.   
  34. /* 回调函数原型 */  
  35. void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);  
  36.   
  37.   
  38. int main()  
  39. {  
  40. pcap_if_t *alldevs;  
  41. pcap_if_t *d;  
  42. int inum;  
  43. int i=0;  
  44. pcap_t *adhandle;  
  45. char errbuf[PCAP_ERRBUF_SIZE];  
  46. u_int netmask;  
  47. char packet_filter[] = "ip and udp";  
  48. struct bpf_program fcode;  
  49.   
  50.     /* 获得设备列表 */  
  51.     if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)  
  52.     {  
  53.         fprintf(stderr,"Error in pcap_findalldevs: %s/n", errbuf);  
  54.         exit(1);  
  55.     }  
  56.       
  57.     /* 打印列表 */  
  58.     for(d=alldevs; d; d=d->next)  
  59.     {  
  60.         printf("%d. %s", ++i, d->name);  
  61.         if (d->description)  
  62.             printf(" (%s)/n", d->description);  
  63.         else  
  64.             printf(" (No description available)/n");  
  65.     }  
  66.   
  67.     if(i==0)  
  68.     {  
  69.         printf("/nNo interfaces found! Make sure WinPcap is installed./n");  
  70.         return -1;  
  71.     }  
  72.       
  73.     printf("Enter the interface number (1-%d):",i);  
  74.     scanf("%d", &inum);  
  75.       
  76.     if(inum < 1 || inum > i)  
  77.     {  
  78.         printf("/nInterface number out of range./n");  
  79.         /* 释放设备列表 */  
  80.         pcap_freealldevs(alldevs);  
  81.         return -1;  
  82.     }  
  83.   
  84.     /* 跳转到已选设备 */  
  85.     for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);  
  86.       
  87.     /* 打开适配器 */  
  88.     if ( (adhandle= pcap_open(d->name,  // 设备名  
  89.                              65536,     // 要捕捉的数据包的部分   
  90.                                         // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容  
  91.                              PCAP_OPENFLAG_PROMISCUOUS,         // 混杂模式  
  92.                              1000,      // 读取超时时间  
  93.                              NULL,      // 远程机器验证  
  94.                              errbuf     // 错误缓冲池  
  95.                              ) ) == NULL)  
  96.     {  
  97.         fprintf(stderr,"/nUnable to open the adapter. %s is not supported by WinPcap/n");  
  98.         /* 释放设备列表 */  
  99.         pcap_freealldevs(alldevs);  
  100.         return -1;  
  101.     }  
  102.       
  103.     /* 检查数据链路层,为了简单,我们只考虑以太网 */  
  104.     if(pcap_datalink(adhandle) != DLT_EN10MB)  
  105.     {  
  106.         fprintf(stderr,"/nThis program works only on Ethernet networks./n");  
  107.         /* 释放设备列表 */  
  108.         pcap_freealldevs(alldevs);  
  109.         return -1;  
  110.     }  
  111.       
  112.     if(d->addresses != NULL)  
  113.         /* 获得接口第一个地址的掩码 */  
  114.         netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;  
  115.     else  
  116.         /* 如果接口没有地址,那么我们假设一个C类的掩码 */  
  117.         netmask=0xffffff;   
  118.   
  119.   
  120.     //编译过滤器  
  121.     if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )  
  122.     {  
  123.         fprintf(stderr,"/nUnable to compile the packet filter. Check the syntax./n");  
  124.         /* 释放设备列表 */  
  125.         pcap_freealldevs(alldevs);  
  126.         return -1;  
  127.     }  
  128.       
  129.     //设置过滤器  
  130.     if (pcap_setfilter(adhandle, &fcode)<0)  
  131.     {  
  132.         fprintf(stderr,"/nError setting the filter./n");  
  133.         /* 释放设备列表 */  
  134.         pcap_freealldevs(alldevs);  
  135.         return -1;  
  136.     }  
  137.       
  138.     printf("/nlistening on %s.../n", d->description);  
  139.       
  140.     /* 释放设备列表 */  
  141.     pcap_freealldevs(alldevs);  
  142.       
  143.     /* 开始捕捉 */  
  144.     pcap_loop(adhandle, 0, packet_handler, NULL);  
  145.       
  146.     return 0;  
  147. }  
  148.   
  149. /* 回调函数,当收到每一个数据包时会被libpcap所调用 */  
  150. void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)  
  151. {  
  152.     struct tm *ltime;  
  153.     char timestr[16];  
  154.     ip_header *ih;  
  155.     udp_header *uh;  
  156.     u_int ip_len;  
  157.     u_short sport,dport;  
  158.     time_t local_tv_sec;  
  159.   
  160.     /* 将时间戳转换成可识别的格式 */  
  161.     local_tv_sec = header->ts.tv_sec;  
  162.     ltime=localtime(&local_tv_sec);  
  163.     strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);  
  164.   
  165.     /* 打印数据包的时间戳和长度 */  
  166.     printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);  
  167.   
  168.     /* 获得IP数据包头部的位置 */  
  169.     ih = (ip_header *) (pkt_data +  
  170.         14); //以太网头部长度  
  171.   
  172.     /* 获得UDP首部的位置 */  
  173.     ip_len = (ih->ver_ihl & 0xf) * 4;  
  174.     uh = (udp_header *) ((u_char*)ih + ip_len);  
  175.   
  176.     /* 将网络字节序列转换成主机字节序列 */  
  177.     sport = ntohs( uh->sport );  
  178.     dport = ntohs( uh->dport );  
  179.   
  180.     /* 打印IP地址和UDP端口 */  
  181.     printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d/n",  
  182.         ih->saddr.byte1,  
  183.         ih->saddr.byte2,  
  184.         ih->saddr.byte3,  
  185.         ih->saddr.byte4,  
  186.         sport,  
  187.         ih->daddr.byte1,  
  188.         ih->daddr.byte2,  
  189.         ih->daddr.byte3,  
  190.         ih->daddr.byte4,  
  191.         dport);  
  192. }  

 

image

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值