I want to write a packet sniffer in c
. Now my code can just count every packet is transmitted in network. I want it to count only http
packets but I don't know how determine those in a packet.This is my code :
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char error[PCAP_ERRBUF_SIZE];
struct bpf_program *fp;
char filter[] = "port 80";
bpf_u_int32 network;
pcap_t *handle = pcap_open_live(argv[1], BUFSIZ, 0, 1000, error);
if (handle == NULL){
printf("Error: %s\n", error);
return 1;
}
if(pcap_compile(handle, &fp, filter,0, network)==-1){
fprintf(stderr, "Error:%s\n", pcap_geterr(handle));
}
if(pcap_setfilter(handle, &fp)==-1){
fprintf(stderr, "Error:%s\n", pcap_geterr(handle));
return 1;
}
pcap_loop(handle, atoi(argv[2]),callback, NULL );
return 0;
}
my callback function just count the number of packets.
If the http packets could be on any port (probably not unless you're testing a local web server), you could first isolate the payload of the packets. "Finding the Data Payload" at https://www.devdungeon.com/content/using-libpcap-c has an example about how to do that.
Then you could compare the first bytes of the data payload with any of the HTTP methods, or with the string "HTTP" to catch responses.