c++ winpcap开发(5)

来源:互联网 发布:下载漫画的软件 编辑:程序博客网 时间:2024/06/04 13:35

过滤引擎是WinPcap(和libpcap)提供的最强大的功能之一。


它提供了一种非常有效的方式来接收网络流量的子集,并且(通常)与WinPcap提供的捕获机制集成。


用于过滤数据包的功能是pcap_compile()和pcap_setfilter()。
pcap_compile()接收一个包含高级布尔(filter)表达式的字符串,并产生一个低级字节代码,可以在包驱动程序中由fileter引擎解释。
布尔表达式的语法可以在本文档的“ 过滤表达式语法”部分找到。


pcap_setfilter()将过滤器与内核驱动程序中的捕获会话相关联。
一旦pcap_setfilter()被调用,相关的过滤器将被应用于来自网络的所有数据包,并且所有符合一致的数据包(即布尔表达式计算为真的数据包)将被实际复制到应用程序。
以下代码显示如何编译和设置过滤器。


请注意,我们必须从描述适配器的pcap_if结构中检索网络掩码,因为pcap_compile()创建的一些过滤器需要它。
在此代码片段中传递给pcap_compile()的过滤器是“ip和tcp”,这意味着“只保留IPv4和TCP两者的数据包并将其传递到应用程序”。

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;    }

原创粉丝点击