pcap_compile() compiles a filter, i.e. takes a string with an high level boolean expression and produces a low-level filtering binary that can be interpreted by the packet driver. The syntax of the boolean expression can be found in the Filtering expression syntax section of this documentation.
pcap_setfilter() associates a filter to a capture session in the kernel driver. From this moment, the filter will be applied to all the packets coming from the network, and all the conformant packets will be actually copied to the application.
The following code shows how to compile and set a filter. Note that we must retrieve the netmask from the pcap_if structure that describes the adapter, because some filters created by pcap_compile() require it.
The filter passed to pcap_compile() in this code snippet is "ip and tcp", that means "keep only the packets that are both IPv4 and TCP and deliver them to the application".
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 you look for a running sample that uses the filtering functions showed in this lesson, look at the next tutorial, Interpreting the packets .
documentation. Copyright (c) 2002-2003 Politecnico di Torino. All rights reserved.