pcap_compile(pcap, &fcode, "tcp", 0, PCAP_NETMASK_UNKNOWN)
Here I have set to 0 and it is working, but I want to know what it does. I am trying to filter tcp packets in a pcap file.
And does pcap_setfilter() reconstructs pcap file into a given fcode?
Well, as stated in the
pcap_compileman page,OK, but of course you might be wondering, "What does that really mean?" To answer that question, I think it's best to provide an example. Consider the following capture filter:
icmp or udp port 53 or bootpc. If you runtcpdump, passing it that filter expression, along with the-dand-Ooptions, it will generate a non-optimized BPF program containing 46 instructions that looks like this:And if you run that same
tcpdumpcommand, but without the-Ooption, thus enabling optimization (the default), then the resulting BPF program contains only 24 instructions that looks like this:Both programs are functionally equivalent but the latter is going to be much more efficient, so in general enabling optimization should be preferred.
If you'd like even more information about optimization, then I would recommend visiting the bpfexam man page where you can even enter an arbitrary capture filter and examine the results.
Regarding pcap_setfilter, as the man page indicates, it is used to specify the filter program (such as those you can see above), which ultimately determines which packets are captured and which ones are discarded.