I am trying to capture packets with libpcap
. Here is my code:
int main (int argc, char **argv) {
char *dev = "eth0";
char errbuf[PCAP_BUFFER_SIZE];
pcap_t *handle;
char filter[] = "tcp and src port 80";
struct bpf_program fp;
bpf_u_int32 mask, net;
handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
pcap_compile(handle, &fp, filter,0,net);
pcap_setfilter(handle, &fp);
pcap_loop(handle, -1, got_packet, NULL);
pcap_freecode(&fp);
pcap_close(handle);
return 0;
}
And
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
static int count = 1;
static int http_count = 1;
const struct sniff_ethernet *ethernet;
const struct sniff_ip *ip;
const struct sniff_tcp *tcp;
int size_ip;
int size_tcp;
int size_payload;
count++;
ethernet = (struct sniff_ethernet*) (packet);
ip = (struct sniff_ip*) (packet + SIZE_ETHERNET);
size_ip = IP_HL(ip)*4;
if (size_ip < 20){
printf("Invalid IP header %d", size_ip);
return;
}
if (ip->ip_p != IPPROTO_TCP){
printf("Not TCP\n");
return;
}
tcp = (struct sniff_tcp*) (packet +SIZE_ETHERNET+size_ip);
size_tcp = TH_OFF(tcp) * 4;
if (size_tcp < 20) {
printf("Invalid TCP header");
return;
}
if ((tcp->th_flags & TH_ACK) != 0) {
const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp);
size_payload = ntohs(ip->ip_len)- (size_ip + size_tcp);
std::cout << payload << "\n";
if (count == 4)
exit(0);
}
The parameters are:
#define SNAP_LEN 65535
#define SIZE_ETHERNET 14
#define ETHER_ADDR_LEN 6
#define PCAP_BUFFER_SIZE 65535
Now, the whole of the fourth packet is not printed. I dumped the packet using tcpdump
and it gets the whole packet but my code does not. Is something wrong here?