广联达土建楼梯怎么画:WinPcap基础知识(第五课:过滤信息)

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 07:18:57
WinPcap提供的最强大的特性之一就是过滤引擎。它是被集成到了winpcap的捕获机制中的,提供了一种非常高效的方法来获取部分网络数据。被用来过滤数据包的函数是 pcap_compile() 和 pcap_setfilter()。
 pcap_compile() 接受一个包含布尔表达式的字符串,生成可以被捕获包驱动中的过滤引擎解释的代码。布尔表达式的语法在这个文档的Filtering expression syntax 那一节(译者注:其实和tcpdump的一样,如果了解tcpdump,可以直接按照tcpdump的语法来写)。
 pcap_setfilter() 绑定一个过滤器到一个在核心驱动中的捕获进程中。一旦 pcap_setfilter() 被调用,这个过滤器就会对网络来的所有数据包进行过滤,所有符合条件的数据包(按照布尔表达式来计算出结果是真的数据包)都会被拷贝给进行捕获的应用程序。
 下面的代码说明了怎样编译和设置一个过滤器。注意我们必须得到说明适配器的 pcap_if 结构中的子网掩码,因为一些被 pcap_compile() 生成的过滤器需要它。这个过滤器中传递给 pcap_compile() 的字符串是 "ip and tcp",意思是“仅仅把IPv4 and TCP 数据包保存下来并交付给应用程序”。view plaincopy to clipboardprint?
if (d->addresses != NULL)  
        /* Retrieve the mask of the first address of the interface */ 
        netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;  
    else 
        /* If the interface is without an address we suppose to be in a C class network */ 
        netmask=0xffffff;   
 
 
    //compile the filter  
    if (pcap_compile(adhandle, &fcode, "ip and tcp", 1, netmask) < 0)  
    {  
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");  
        /* Free the device list */ 
        pcap_freealldevs(alldevs);  
        return -1;  
    }  
      
    //set the filter  
    if (pcap_setfilter(adhandle, &fcode) < 0)  
    {  
        fprintf(stderr,"\nError setting the filter.\n");  
        /* Free the device list */ 
        pcap_freealldevs(alldevs);  
        return -1;  
    } 
if (d->addresses != NULL)
        /* Retrieve the mask of the first address of the interface */
        netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
    else
        /* If the interface is without an address we suppose to be in a C class network */
        netmask=0xffffff;
    //compile the filter
    if (pcap_compile(adhandle, &fcode, "ip and tcp", 1, netmask) < 0)
    {
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
   
    //set the filter
    if (pcap_setfilter(adhandle, &fcode) < 0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
 如果你想看一些在这节课中讲述的使用过滤功能的代码,请看下节课中的例子,Interpreting the packets. 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/qsycn/archive/2009/08/18/4458607.aspx