我正在学习用c编写pcap代码。下面,我编写了一个简单的C代码,用于自动检测设备进行加密,获取IP和子网掩码,获取链路层标头并过滤流量,然后打印数据包大小。
代码成功遵从,但被卡在
发现网络设备:wlo1
运行时。卸下过滤器部件确实会打印数据包大小。并删除包的主要部分;该程序符合要求并成功运行。
我认为我对过滤部分缺乏了解。
我使用linux编译:gcc程序名-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;
}
如果wlo1
在“受保护”网络(使用WEP或WPA / WPA2 / WPA3在链路层上加密流量的网络)中以监视模式捕获,则任何在链路层上工作的过滤器-例如一个TCP / UDP层过滤器(“端口80”是-)将不起作用,因为传递到过滤代码的数据包将加密802.11有效负载,因此过滤器将无法对其使用。
因此,没有数据包将通过过滤器。