TTR Networks

What is BPF?

Berkeley Packet Filter

BPF (Berkeley Packet Filter) is an in-kernel packet filter that lets capture tools like tcpdump receive only the packets that match a filter.

Copying every packet from the kernel to a capture program is expensive, especially on a busy interface. BPF solves this with a small virtual machine in the kernel that runs a filter program against each packet and only passes matches up to user space. You rarely write that program directly. Instead you give tcpdump a readable filter expression, libpcap compiles it into BPF instructions, and the kernel runs them. The expression syntax (documented in the pcap-filter manual page) is built from primitives joined with and, or and not:

  • host 203.0.113.20, src net 198.51.100.0/24
  • tcp port 80, udp port 53, portrange 33434-33534
  • icmp, ip6, arp, vlan

So tcpdump -n -i eth0 'tcp port 80 and host 203.0.113.20' shows only web traffic to or from one host. Running tcpdump -d with the same expression prints the compiled instructions, which is a good way to see what a filter really does.

A few habits make BPF filters reliable. Quote the whole expression so the shell doesn't interpret parentheses or !. Remember that port 80 matches either direction, while dst port 80 matches only one. A filter on an address will miss packets on a tagged interface unless you include vlan. The same filters work when reading saved pcap files with -r, so a broad capture can be re-examined with many narrow filters. Linux has since grown eBPF, a much more general extension used for tracing, firewalls and load balancing; capture filters use the older, classic form. The Packets That Never Come Back lesson uses tcpdump filters to find where packets disappear.

Lessons that use BPF

  • Packets That Never Come BackTeaches this term · Intermediate · 75 min

    Advanced packet capture with tcpdump, and how to find where packets die on a VyOS network: missing NAT and return routes, asymmetric routing through a stateful firewall, and MTU black holes, all diagnosed on a real VyOS router.

Related terms