Guides

2.5 - Setting a packet filter

It is possible to set a packet filter directly on the pcap capture and only have packets delivered to your application that match and pass the filter expression.

The filter is built from a human friendly textual expression using libpcap filter syntax. The expression, presented as a string, is filter compiled to a PcapBpfProgram which holds the binary representation of the filter expression, and then the bpf program is set on the pcap capture using Pcap.setFilter() call.

PcapBpfProgram program = new PcapBpfProgram();
String expression = "host 192.168.1.1";
int optimize = 0;         // 0 = false
int netmask = 0xFFFFFF00; // 255.255.255.0
		
if (pcap.compile(program, expression, optimize, netmask) != Pcap.OK) {
  System.err.println(pcap.getErr());
  return;
}
		
if (pcap.setFilter(program) != Pcap.OK) {
  System.err.println(pcap.getErr());
  return;		
}

(View complete SetFilterExample.java)

More filter syntax examples

(Source: tcpdump man page)

       To  print  all  packets arriving at or departing from sun­
       down:
              host sundown

       To print traffic between helios and either hot or ace:
              host helios and ( hot or ace )

       To print all IP packets between ace and  any  host  except
       helios:
              ip host ace and not helios

       To  print  all  traffic  between  local hosts and hosts at
       Berkeley:
              net ucb-ether

       To print all ftp traffic through  internet  gateway  snup:
       (note  that  the expression is quoted to prevent the shell
       from (mis-)interpreting the parentheses):
              gateway snup and (port ftp or ftp-data)

       To print traffic neither sourced  from  nor  destined  for
       local  hosts  (if you gateway to one other net, this stuff
       should never make it onto your local net).
              ip and not net localnet

       To print the start and end packets (the SYN and FIN  pack­
       ets)  of  each  TCP conversation that involves a non-local
       host.
              tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet

       To print IP packets longer than  576  bytes  sent  through
       gateway snup:
              gateway snup and ip[2:2] > 576

       To  print  IP broadcast or multicast packets that were not
       sent via ethernet broadcast or multicast:
              ether[0] & 1 = 0 and ip[16] >= 224

       To  print   all   ICMP   packets   that   are   not   echo
       requests/replies (i.e., not ping packets):
              icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply

(Note: the quoted examples above removed tcpdump keyword and certain shell escape sequences from the examples, as this is irrelevant for jNetPcap since the filter string is passed directly to Pcap.setFilter)