WinPcap編程【6】過濾、分析數據包

WinPcap和Libpcap的最強大的特性之一,是擁有過濾數據包的引擎。 它提供了有效的方法去獲取網絡中的某些數據包,這也是WinPcap捕獲機制中的一個組成部分。 用來過濾數據包的函數是 pcap_compile() 和pcap_setfilter() 。

pcap_compile() 它將一個高層的布爾過濾表達式編譯成一個能夠被過濾引擎所解釋的低層的字節碼。有關布爾過濾表達式的語法可以參見 Filtering expression syntax 這一節的內容。

pcap_setfilter() 將一個過濾器與內核捕獲會話向關聯。當 pcap_setfilter() 被調用時,這個過濾器將被應用到來自網絡的所有數據包,並且,所有的符合要求的數據包 (即那些經過過濾器以後,布爾表達式爲真的包) ,將會立即複製給應用程序。

現在,我們可以捕捉並過濾網絡流量了,那就讓我們學以致用,來做一個簡單使用的程序吧。

在本講中,我們將會利用上一講的一些代碼,來建立一個更實用的程序。 本程序的主要目標是展示如何解析所捕獲的數據包的協議首部。這個程序可以稱爲UDPdump,打印一些網絡上傳輸的UDP數據的信息。

我們選擇分析和現實UDP協議而不是TCP等其它協議,是因爲它比其它的協議更簡單,作爲一個入門程序範例,是很不錯的選擇。讓我們看看代碼:

  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

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