Files
nudtns2026spring/Sniffing_Spoofing/volumes/sniffer.c
2026-04-07 20:49:20 +08:00

40 lines
1.1 KiB
C

#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
printf("Got a packet\n");
}
int main() {
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
char filter_exp[] = "icmp";
bpf_u_int32 net;
// Step 1: Open pcap session on the interface
handle = pcap_open_live("br-c031fbf1a197", BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device: %s\n", errbuf);
return 2;
}
// Step 2: Compile filter_exp into BPF code
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
return 2;
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
return 2;
}
// Step 3: Capture packets
printf("Sniffing ICMP packets using C and libpcap...\n");
pcap_loop(handle, -1, got_packet, NULL);
pcap_close(handle);
return 0;
}