WinPcap笔记:分析数据包(1)

现在,我们可以捕获并过滤网络流量了,那就简单协议个程序分析网络数据包。

这里我们只是解析所捕获数据包的首部,打印一些数据包首部的信息。我们以UDP为例,因为UDP比较简单。

首先,应该介绍下网络数据包的格式。网络中的数据包每经过一个层次都会加上那个层的报头来标注一些重要的信息。捕获到的数据包首先有个mac报头,14字节,包含6字节目的mac地址、6字节源mac地址,和2字节上一层协议。这里我们不关注mac报头,所以省略。

接下来是IP数据包,包的格式如下图:

WinPcap笔记:分析数据包(1)

IP数据包有20字节的报头,报头格式如下图:

WinPcap笔记:分析数据包(1)


WinPcap没有给出一个保存IP报头信息的结构体,所以需要我们自己定义。下面是IP报头的定义:

[cpp] view plain copy
  1. /* IPv4 首部 */  
  2. typedef struct ip_header {  
  3.     u_char  ver_ihl;        // 版本 (4 bits) + 首部长度 (4 bits)  
  4.     u_char  tos;            // 服务类型(Type of service)   
  5.     u_short tlen;           // 总长(Total length)   
  6.     u_short identification; // 标识(Identification)  
  7.     u_short flags_fo;       // 标志位(Flags) (3 bits) + 段偏移量(Fragment offset) (13 bits)  
  8.     u_char  ttl;            // 存活时间(Time to live)  
  9.     u_char  proto;          // 协议(Protocol)  
  10.     u_short crc;            // 首部校验和(Header checksum)  
  11.     ip_address  saddr;      // 源地址(Source address)  
  12.     ip_address  daddr;      // 目的地址(Destination address)  
  13.     u_int   op_pad;         // 选项与填充(Option + Padding)  
  14. }ip_header;  

我们可以通过首部长度得到UDP数据包的位置。下面的代码计算首部长度:

[cpp] view plain copy
  1. ip_len = (ih->ver_ihl & 0xf) * 4;  

得到首部长度后就可以得到UDP的位置了。下图是UDP报头的格式:
WinPcap笔记:分析数据包(1)

同样,UDP结构也需要我们自己定义:
[cpp] view plain copy
  1. /* UDP 首部*/  
  2. typedef struct udp_header {  
  3.     u_short sport;          // 源端口(Source port)  
  4.     u_short dport;          // 目的端口(Destination port)  
  5.     u_short len;            // UDP数据包长度(Datagram length)  
  6.     u_short crc;            // 校验和(Checksum)  
  7. }udp_header;  

这里涉及到小端法和大端法。下面简单介绍一下。
《UNXI网络编程》定义:术语“小端”和“大端”表示多字节值的哪一端(小端或大端)存储在该值的起始地址。小端存在起始地址,即是小端字节序;大端存在起始地址,即是大端字节序。
也就是说,小端法(Little-Endian)将低位字节存储在内存的低地址即起始地址处,高字节存储在高地址;而大端法(Big-Endian)将低位字节存储在高地址,将高位字节存储在低地址处。
举个例子,对于整形0x12345678。它在大端法和小端法的系统内中,分别如下图所示的方式存放:
WinPcap笔记:分析数据包(1)

还有一个概念叫网络字节序,我们知道网络上的数据流是字节流,对于一个多字节数值,在进行网络传输的时候,先传递哪个字节?也就是说,当接收端收到第一个字节的时候,它是将这个字节作为高位还是低位来处理呢? 
网络字节序定义:收到的第一个字节被当作高位看待,这就要求发送端发送的第一个字节应当是高位。而在发送端发送数据时,发送的第一个字节是该数字在内存中起始地址对应的字节。可见多字节数值在发送前,在内存中数值应该以大端法存放。 
网络字节序说是大端字节序。 
比如我们经过网络发送0x12345678这个整形,在80X86平台中,它是以小端法存放的,在发送前需要使用系统提供的htonl将其转换成大端法存放,如下图:
WinPcap笔记:分析数据包(1)

因此,对于多字节属性,需要使用函数在网络字节序和主机字节序中转换。
下面是程序的主要代码,将UDP的源IP地址、源端口、目的IP地址、目的端口打印出来:
[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. 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. }  

运行结果如下:
WinPcap笔记:分析数据包(1)
原文地址:http://blog.csdn.net/u012877472/article/details/49846867