我正在学习用 c 语言编写 pcap 代码。下面我编写了一个简单的C代码来自动检测设备进行嗅探,获取IP和子网掩码,获取链路层 header 并过滤流量,然后打印数据包大小。
代码成功遵守,但卡在
发现网络设备:wlo1
运行时。删除过滤器部分确实会打印数据包大小。并去除打印包部分;程序符合要求并成功运行。
我认为我缺乏对过滤部分的理解。
我使用(在Linux上)进行编译:gcc program_name -lpcap
代码的输出是: 找到网络设备:wlo1
wlo1是WLAN设备
#include <stdio.h>
#include <pcap.h>
int main(int argc, char *argv[]){
char *dev; //device automatically detected for sniffing
char errbuf[PCAP_ERRBUF_SIZE]; //error string
pcap_t *handle; //session hnadle
struct bpf_program fp; //The compiled filter expression
char filter_exp[] = "port 23"; //The filter expression
bpf_u_int32 mask; //The netmask of our sniffing device
bpf_u_int32 net; //The IP of our sniffing device
struct pcap_pkthdr header;
const unsigned char *packet;
//device detection block
dev = pcap_lookupdev(errbuf);
if (dev == NULL){
printf("Error finding device: %s\n", errbuf);
return 1;
}
printf("Network device found: %s\n", dev);
//opening device for sniffing
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if(handle == NULL){
fprintf(stderr,"Couldn't open device %s : %s\n",dev,errbuf);
return 1;
}
// //check for link-layer header of the device
if(pcap_datalink(handle) != DLT_EN10MB){ //for ethernet data link layer
if(pcap_datalink(handle) != DLT_IEEE802_11){ //for wlan data link layer
fprintf(stderr, "Device %s doesn't provide WLAN headers - not supported\n", dev);
return 1;
}
else{
fprintf(stderr, "Device %s doesn't provide Ethernet headers - not supported\n", dev);
return 1;
}
}
//block to get device ip and subnet mask
if(pcap_lookupnet(dev, &net, &mask, errbuf) == -1){
fprintf(stderr, "Can't get netmask for device %s\n", dev);
net = 0;
mask = 0;
}
//block for filtering traffic we want to sniff
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 1;
}
if(pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
return 1;
}
/* Grab a packet */
packet = pcap_next(handle, &header);
/* Print its length */
printf("Jacked a packet with length of [%d]\n", header.len);
/* And close the session */
pcap_close(handle);
return 0;
}
最佳答案
如果 wlo1
在“ protected ”网络(使用 WEP 或 WPA/WPA2/WPA3 在链路层加密流量的网络)上以监控模式进行捕获,则任何在上面工作的过滤器链路层 - 例如 TCP/UDP 层过滤器(“端口 80”) - 将不起作用,因为传递到过滤代码的数据包将加密 802.11 有效负载,因此过滤器将无法工作他们。
因此,没有数据包会通过过滤器。
关于c - 数据包捕获 C 代码不会终止显示捕获的数据包数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223667/