我正在学习用c编写pcap代码。下面我写了一个简单的c代码来自动检测设备,用于嗅探、获取ip和子网掩码、获取链路层报头和过滤流量,然后打印数据包大小。
代码成功编译,但在
找到网络设备: wlo1
运行时。删除过滤器部件会打印数据包大小。删除打印包部分,程序编译并运行成功。
我想我对过滤部分缺乏理解。
我使用(在linux上)编译: gcc program_name -lpcap
代码的输出是:找到网络设备: wlo1
wlo1是无线局域网设备
#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;
}发布于 2019-10-04 02:32:57
如果wlo1在“受保护”网络(在链路层使用WEP或WPA/wpa2/wpa3加密流量的网络)上以监控模式捕获,则任何工作在链路层之上的过滤器--例如TCP/UDP层过滤器,即“端口80”--都将不起作用,因为在传送到过滤代码时,数据包将加密802.11有效载荷,因此过滤器不会对它们起作用。
因此,任何数据包都不会通过过滤器。
https://stackoverflow.com/questions/58223667
复制相似问题