This is a static archive of our old Q&A Site. Please post any new questions and answers at ask.wireshark.org.

How to filter packets with BPF in a C program when they’re not read from a live capture or pcap/pcap-ng file?

0

I am developing a component of a software on processing packets. The input comes as a pointer to an array of packets (each packet is a struct, with a field for pointer to packet data and a field for packet len). How would I use BPF rule to help me skip some packets, it will greatly reduce the processing time since I don't need to waste time on packets that are not useful.

I know libpcap will allow this, but it assume the input is is a file in the form of pcap format.

Thanks.

asked 31 Jul '15, 07:27

pktUser1001's gravatar image

pktUser1001
201495054
accept rate: 12%

edited 31 Jul '15, 16:02

Guy%20Harris's gravatar image

Guy Harris ♦♦
17.4k335196


One Answer:

2

Use pcap_open_dead() to get a pcap_t * with whatever the appropriate DLT_ value is for the packet data.

Use pcap_compile() to compile your filter into BPF code, if you haven't hand-written a BPF program.

For each packet, construct a struct pcap_pkthdr (you don't need to give it a time stamp, as the filter doesn't look at that, and use the packet length for both the captured length and the on-the-network length), and use pcap_offline_filter() to run the filter against the packet (or, if you have an older version of libpcap that doesn't have pcap_offline_filter(), directly call bpf_filter(), which is in libpcap).

answered 31 Jul '15, 10:58

Guy%20Harris's gravatar image

Guy Harris ♦♦
17.4k335196
accept rate: 19%

Thank you so much Guy! Really helpful. Wish I can vote you up multiple times.

(31 Jul '15, 15:23) pktUser1001