【发布时间】:2015-10-23 04:36:00
【问题描述】:
我是 C 的新手,有点困惑。我已经阅读了一些关于这个问题的主题,但没有一个对我有用。我正在尝试使用 libpcap 捕获 wlan0 数据包,但出现问题。 pcap_next() 函数返回 null 但我不知道为什么。这是我的代码:
#include <pcap.h>
#include <stdio.h>
#include <string.h>
void dump(const unsigned char *data_buffer, const unsigned int length) {
unsigned char byte;
unsigned int i, j;
for(i=0; i < length; i++) {
byte = data_buffer[i];
printf("%02x ", data_buffer[i]); // Display byte in hex.
if(((i%16)==15) || (i==length-1)) {
for(j=0; j < 15-(i%16); j++)
printf(" ");
printf("| ");
for(j=(i-(i%16)); j <= i; j++) { // Display printable bytes from line.
byte = data_buffer[j];
if((byte > 31) && (byte < 127)) // Outside printable char range
printf("%c", byte);
else
printf(".");
}
printf("\n"); // End of the dump line (each line is 16 bytes)
} // End if
} // End for
}
int main() {
struct pcap_pkthdr header;
const u_char *packet;
char errbuf[PCAP_ERRBUF_SIZE];
char *device;
pcap_t *pcap_handle;
int i;
device = "wlan0";
printf("Sniffing on device %s\n", device);
pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf);
for(i=0; i < 3; i++) {
packet = pcap_next(pcap_handle, &header);
printf("Got a %d byte packet\n", header.len);
dump(packet, header.len);
}
pcap_close(pcap_handle);
}
我得到的输出是
在设备 wlan0 上嗅探
得到一个 0 字节数据包
得到一个 0 字节数据包
得到一个 0 字节数据包
这就是我编译 gcc -o test test.c -l pcap 并以 root 身份运行程序的方式。谢谢。
【问题讨论】:
-
你听说过代码缩进吗?
-
如果返回 NULL,
errbuf将填写适当的错误消息。 -
对不起,它的 pcap_next() 返回 null
标签: c wireless pcap libpcap packet-capture