Using Filters

/* first we need to compile the filter.           */
/* Note: the filter requires knowing our netmask. */
bpf_u_int32 netmask;
inet_pton(AF_INET, "255.255.255.0", &netmask);

struct bpf_program filter;
char* filter_str = "port 22";
rc = pcap_compile(pc, &filter, filter_str, 1 /*optimize*/, netmask);
if (rc == -1) {
    fprintf(stderr, "Failed compiling filter '%s' - %s\n",
            filter_str, pcap_geterr(pc));
    exit(1);
}

/* then set this program as our filter. */
rc = pcap_setfilter(pc, &filter);
if (rc == -1) {
    fprintf(stderr, "Failed setting filter for pcap - %s\n",
            pcap_geterr(pc));
    exit(1);
}

/* after we're done with the filter struct - free it. */
pcap_freecode(&filter);
Originally written by Valid HTML 4.01!guy keren