使用WinPcap编程(3)——设置过滤器

      设置过滤器要用到两个函数,一个是pcap_compile(),另一个是pcao_setfilter()。他们的函数原型如下所示:

int pcap_compile (pcap_t *p, struct bpf_program *fp, char *str, int optimize, bpf_u_int32 netmask)

      1、p是一个打开的网络设备的描述符。

      2、fp是一个指针,用来存储一个编译好的过滤码。我们需要提前设置 struct bpf_program fcode 在这里使用。

      3、str是字符串(以\0结尾),它指定一个字符串性质的过滤描述,通过这个函数把这个描述转换成可供内部使用的过滤码。

      4、optimize设置是否要进行优化。一般为1。

      5、netmask就是我们所打开的设备的netmask,不知道这个怎么用。一般用d->addresses->netmask这个就可以了。

      return: 如果出错的话,就会返回一个小于0的值。

      然后就是设置这个过滤器:

int pcap_setfilter (pcap_t *p, struct bpf_program *fp)

      1、p就是一个已经打开的设备的描述符。     

      2、fp是用上面的函数编译好的过滤码,现在把这个过滤码设置到系统中去。

      附上一个代码:

#define _CRT_SECURE_NO_WARNINGS

#include "pcap.h"

void packet_handler(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data);

int main()
{
	pcap_t *cap_ins_des;
	pcap_if_t *alldevs;
	pcap_if_t *d;
	char source[PCAP_BUF_SIZE];
	char errbuf[PCAP_ERRBUF_SIZE];
	int i;
	u_int netmask;
	char packet_filter[] = "ip and udp";	// the filter
	struct bpf_program fcode;	// used in pcap_compile()

	/* set the source */
	if (pcap_createsrcstr(source, PCAP_SRC_IFLOCAL, NULL, NULL, NULL, errbuf) == -1) {
		printf("%s\n", errbuf);
		exit(-1);
	}
	printf("source: %s\n", source);

	/* find all devices */
	if (pcap_findalldevs_ex(source, NULL, &alldevs, errbuf) == -1) {
		printf("%s\n", errbuf);
		exit(-1);
	}

	/* choose one devices */
	d = alldevs;
	while (d != NULL) {
		printf("%s, %s\n", d->name, d->description);
		d = d->next;
	}
	scanf("%d", &i);
	d = alldevs;
	while (--i)
		d = d->next;
	printf("selected device: %s\n", d->name);

	/* open one device */ 
	cap_ins_des = pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf);
	if (cap_ins_des == NULL) {
		printf("%s\n", errbuf);
		pcap_freealldevs(alldevs);
		exit(-1);
	}

	/* get the netmask, used at compiling the filter */
	if (d->addresses != NULL)
		netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;	/*@#$%^&*!*/
	else
		netmask = 0xffffff;	/* 255.25.255.0 */

	// netmask = 0;

	/* compile the filter */
	if (pcap_compile(cap_ins_des, &fcode, packet_filter, 1, netmask) < 0) {
		printf("Error\n");
		pcap_freealldevs(alldevs);
		exit(-1);
	}

	/* set the filter */
	if (pcap_setfilter(cap_ins_des, &fcode) < 0) {
		printf("Error\n");
		pcap_freealldevs(alldevs);
		exit(-1);
	}

	pcap_freealldevs(alldevs);

	/* start the capture */
	pcap_loop(cap_ins_des, 30, packet_handler, NULL);

	return 0;
}

void packet_handler(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
{
	printf("in packet handler\n");
	return;
}
原文地址:https://www.cnblogs.com/wangshuo/p/2114926.html