cad导入广联达不显示:WinPcap基础知识(第六课:翻译数据包)

来源:百度文库 编辑:偶看新闻 时间:2024/04/29 02:43:25

现在我们已经能够捕获并且过滤网络数据包,下面我们就把我们的知识运用到一个简单的“真实的”应用程序中去。
 在这节课中我们将从前面的课程中拷贝代码并用它们来构造出一个更有用途的程序。这个程序主要的目的就是说明怎样分析和解释我们已经捕获的数据包的协议结构。最终的应用程序,叫做UDPdump,会打印出一个在我们的网络中的UDP数据包的概要。
 在开始阶段我们选择分析并显示UDP协议,因为UDP协议比其他的协议比如TCP协议更容易理解,从而非常适合作为初始阶段的例子。还是让我们开始看代码吧:

view plaincopy to clipboardprint?

  1. #define HAVE_REMOTE   
  2. #include    
  3.   
  4. #pragma comment(lib,"wpcap.lib")   
  5. #pragma comment(lib,"Ws2_32.lib")   
  6.   
  7. /* 4 bytes IP address */  
  8. typedef struct ip_address{   
  9.     u_char byte1;   
  10.     u_char byte2;   
  11.     u_char byte3;   
  12.     u_char byte4;   
  13. }ip_address;   
  14.   
  15. /* IPv4 header */  
  16. typedef struct ip_header{   
  17.     u_char  ver_ihl;        // Version (4 bits) + Internet header length (4 bits)   
  18.     u_char  tos;            // Type of service    
  19.     u_short tlen;           // Total length    
  20.     u_short identification; // Identification   
  21.     u_short flags_fo;       // Flags (3 bits) + Fragment offset (13 bits)   
  22.     u_char  ttl;            // Time to live   
  23.     u_char  proto;          // Protocol   
  24.     u_short crc;            // Header checksum   
  25.     ip_address  saddr;      // Source address   
  26.     ip_address  daddr;      // Destination address   
  27.     u_int   op_pad;         // Option + Padding   
  28. }ip_header;   
  29.   
  30. /* UDP header*/  
  31. typedef struct udp_header{   
  32.     u_short sport;          // Source port   
  33.     u_short dport;          // Destination port   
  34.     u_short len;            // Datagram length   
  35.     u_short crc;            // Checksum   
  36. }udp_header;   
  37.   
  38. /* prototype of the packet handler */  
  39. void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);   
  40.   
  41.   
  42. main()   
  43. {   
  44. pcap_if_t *alldevs;   
  45. pcap_if_t *d;   
  46. int inum;   
  47. int i=0;   
  48. pcap_t *adhandle;   
  49. char errbuf[PCAP_ERRBUF_SIZE];   
  50. u_int netmask;   
  51. char packet_filter[] = "ip and udp";   
  52. struct bpf_program fcode;   
  53.   
  54.     /* Retrieve the device list */  
  55.     if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)   
  56.     {   
  57.         fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);   
  58.         exit(1);   
  59.     }   
  60.        
  61.     /* Print the list */  
  62.     for(d=alldevs; d; d=d->next)   
  63.     {   
  64.         printf("%d. %s", ++i, d->name);   
  65.         if (d->description)   
  66.             printf(" (%s)\n", d->description);   
  67.         else  
  68.             printf(" (No description available)\n");   
  69.     }   
  70.   
  71.     if(i==0)   
  72.     {   
  73.         printf("\nNo interfaces found! Make sure WinPcap is installed.\n");   
  74.         return -1;   
  75.     }   
  76.        
  77.     printf("Enter the interface number (1-%d):",i);   
  78.     scanf("%d", &inum);   
  79.        
  80.     if(inum < 1 || inum > i)   
  81.     {   
  82.         printf("\nInterface number out of range.\n");   
  83.         /* Free the device list */  
  84.         pcap_freealldevs(alldevs);   
  85.         return -1;   
  86.     }   
  87.   
  88.     /* Jump to the selected adapter */  
  89.     for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);   
  90.        
  91.     /* Open the adapter */  
  92.     if ( (adhandle= pcap_open(d->name,  // name of the device   
  93.                              65536,     // portion of the packet to capture.    
  94.                                         // 65536 grants that the whole packet will be captured on all the MACs.   
  95.                              PCAP_OPENFLAG_PROMISCUOUS,         // promiscuous mode   
  96.                              1000,      // read timeout   
  97.                              NULL,      // remote authentication   
  98.                              errbuf     // error buffer   
  99.                              ) ) == NULL)   
  100.     {   
  101.         fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n");   
  102.         /* Free the device list */  
  103.         pcap_freealldevs(alldevs);   
  104.         return -1;   
  105.     }   
  106.        
  107.     /* Check the link layer. We support only Ethernet for simplicity. */  
  108.     if(pcap_datalink(adhandle) != DLT_EN10MB)   
  109.     {   
  110.         fprintf(stderr,"\nThis program works only on Ethernet networks.\n");   
  111.         /* Free the device list */  
  112.         pcap_freealldevs(alldevs);   
  113.         return -1;   
  114.     }   
  115.        
  116.     if(d->addresses != NULL)   
  117.         /* Retrieve the mask of the first address of the interface */  
  118.         netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;   
  119.     else  
  120.         /* If the interface is without addresses we suppose to be in a C class network */  
  121.         netmask=0xffffff;    
  122.   
  123.   
  124.     //compile the filter   
  125.     if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )   
  126.     {   
  127.         fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");   
  128.         /* Free the device list */  
  129.         pcap_freealldevs(alldevs);   
  130.         return -1;   
  131.     }   
  132.        
  133.     //set the filter   
  134.     if (pcap_setfilter(adhandle, &fcode)<0)   
  135.     {   
  136.         fprintf(stderr,"\nError setting the filter.\n");   
  137.         /* Free the device list */  
  138.         pcap_freealldevs(alldevs);   
  139.         return -1;   
  140.     }   
  141.        
  142.     printf("\nlistening on %s...\n", d->description);   
  143.        
  144.     /* At this point, we don't need any more the device list. Free it */  
  145.     pcap_freealldevs(alldevs);   
  146.        
  147.     /* start the capture */  
  148.     pcap_loop(adhandle, 0, packet_handler, NULL);   
  149.        
  150.     return 0;   
  151. }   
  152.   
  153. /* Callback function invoked by libpcap for every incoming packet */  
  154. void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)   
  155. {   
  156.     struct tm *ltime;   
  157.     char timestr[16];   
  158.     ip_header *ih;   
  159.     udp_header *uh;   
  160.     u_int ip_len;   
  161.     u_short sport,dport;   
  162.   
  163.     /* convert the timestamp to readable format */  
  164.     ltime=localtime(&header->ts.tv_sec);   
  165.     strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);   
  166.   
  167.     /* print timestamp and length of the packet */  
  168.     printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);   
  169.   
  170.     /* retireve the position of the ip header */  
  171.     ih = (ip_header *) (pkt_data +   
  172.         14); //length of ethernet header   
  173.   
  174.     /* retireve the position of the udp header */  
  175.     ip_len = (ih->ver_ihl & 0xf) * 4;   
  176.     uh = (udp_header *) ((u_char*)ih + ip_len);   
  177.   
  178.     /* convert from network byte order to host byte order */  
  179.     sport = ntohs( uh->sport );   
  180.     dport = ntohs( uh->dport );   
  181.   
  182.     /* print ip addresses and udp ports */  
  183.     printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",   
  184.         ih->saddr.byte1,   
  185.         ih->saddr.byte2,   
  186.         ih->saddr.byte3,   
  187.         ih->saddr.byte4,   
  188.         sport,   
  189.         ih->daddr.byte1,   
  190.         ih->daddr.byte2,   
  191.         ih->daddr.byte3,   
  192.         ih->daddr.byte4,   
  193.         dport);   
  194. }  

 

首先,我们设置过滤器为”ip and udp”。这样,我们保证packet_handler()将只接收基于IPv4的udp数据包;这样可以简单化分解(parsing)过程和提高程序的执行效率。

 

 

     我们还创建了一对用来描述IP和UDP头信息的结构体。这两个结构被packet_handler()调用来定位各种各样的信息头域。

 

 

     Packet_handler(),尽管限制为只为一个协议解剖(UDP OVER IPV4),向我们展示了象tcpdump/windump这种复杂的探测是怎么样对网络信息进行解码的。首先,因为我们对MAC头部不感兴趣,所以我们忽略它。为了简单起见,在开始启动捕获前,我们用pcap_datalink()在MAC层做一个检查,这样UDPdump就会仅仅在以太网上进行工作。这样我们能保证MAC头部是14个字节。

 

 

     IP头在MAC头之后,我们从IP头中获得源IP地址和目的IP地址。

 

 

     到了UDP头部就有点复杂,因为IP头没有一个固定的长度。因此,我们使用接口首部长度域来得到大小。一旦我们知道了UDP首部的位置,我们就可以从中提取出源端口和目的端口号。

 

 

     提取的信息打印在屏幕上,结果象下面所示:

 

 

1.     {A7FD048A-5D4B-478E-B3C1-34401AC3B72F} (Xircom t 10/100 Adapter)
Enter the interface number (1-2):1

listening on Xircom CardBus Ethernet 10/100 Adapter...
16:13:15.312784 len:87 130.192.31.67.2682 -> 130.192.3.21.53
16:13:15.314796 len:137 130.192.3.21.53 -> 130.192.31.67.2682

16:13:15.322101 len:78 130.192.31.67.2683 -> 130.192.3.21.53

 

每一行代表一个数据包。