I'm writing a C application which uses the pcap library to log how much data (matching various packet filters) has passed through a network card. The values that I'm getting seem much too low to be correct, but I'm not sure what I'm doing wrong.
The test code below exhibits the same behavior (error checking omitted for clarity):
#include <stdio.h>
#include <pcap.h>
static int total=0;
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data){
total += header->len;
printf("%d\n", total);
}
int main(){
char errbuf[1024];
pcap_t *adhandle = pcap_open_live("en1", 65535, 0, 0, errbuf);
pcap_setnonblock(adhandle, 1, errbuf);
struct bpf_program fcode;
pcap_compile(adhandle, &fcode, "port 80", 1, 0);
pcap_setfilter(adhandle, &fcode);
while(1){
pcap_dispatch(adhandle, -1, packet_handler, NULL);
sleep(1);
}
return 0;
}
I'm working on OSX, compiling with gcc, and I've tried downloading over wi-fi and wired ethernet. I expect the code above to print out the number of bytes that have matched the filter (in this case all HTTP traffic) but when I download a test file 4,357,017 bytes in size I get a value of only 95,133. My test file was a zip archive so I don't think HTTP compression can account for the difference.
Update: I've modified the code to print out the size of each packet, as well as the running total, and also to report only the incoming packets (changed the filter to "src port 80"). This gives lots of packet lengths of '1514' which I think is related to the MTU value of 1500, however the total remains far too low.