2

我正在“wlan”接口上使用 libpcap 库编写一个 pcaket 嗅探器程序。我想过滤捕获的数据包,以便只处理信标帧。因此,我为此编写了以下代码:

const char *str = "wlan subtype beacon";
printf("debug stmt1\n");

struct bpf_program *fp;
printf("debug stmt2\n");

if((pcap_compile(pkt_handle, fp, str, 1, PCAP_NETMASK_UNKNOWN)==-1)
{
    pcap_perror(pkt_handle, "Compile");
}
printf("debug stmt3\n"):

但是在编译时,我在 pcap_compile() 语句上遇到了分段错误:

debug stmt1
debug stmt2
Segmentation fault

那么,可能是什么问题?

操作系统:Ubuntu 10.10

更新:

我在 pcap_activate() 语句之前移动了 pcap_compile() 语句。该程序运行良好,仅捕获信标帧。但是,pcap_compile() 似乎仍然返回 -1,我在输出中得到以下语句:

Compile: 802.11 link-layer types supported only on 802.11

可能是什么问题呢?我正在使用 Netgear USB 无线网卡。
更新2:

根据 nos 的建议,我进行了以下更改:

struct bpf_program *fp = (struct bpf_program *)malloc(sizeof(struct bpf_program));

但是,我仍然收到相同的消息:

Compile: 802.11 link-layer types supported only on 802.11

知道那条消息是什么意思吗?

更新 3:
我还包含以下代码以确保我的 pcap 句柄指向正确的接口:

int *dlt_buf;
int n;
n = pcap_list_datalinks(pkt_handle, &dlt_buf);
printf("n = %d\n",n);
if(n == -1)
{
    pcap_perror(pkt_handle, "Datalink_list");
}
else
{
    printf("The list of datalinks supported are\n");
    int i;
    for(i=0; i<n; i++)
        printf("%d\n",dlt_buf[i]);
    const char *str1 = pcap_datalink_val_to_name(dlt_buf[0]);
    const char *str2 = pcap_datalink_val_to_description(dlt_buf[0]);
    printf("str1 = %s\n",str1);
    printf("str2 = %s\n",str2);
    pcap_free_datalinks(dlt_buf);
}


这是我得到的输出:

n = 1
The list of datalinks supported are
127
str1 = IEEE802_11_RADIO
str2 = 802.11 plus radiotap header


所以,我的 pcap 句柄指向正确的接口。但我仍然收到该错误消息。

4

1 回答 1

3

如前所述,崩溃是因为 fp 没有指向某个东西。如果一个函数接受一个类型为“{something} *”的参数,那并不意味着你需要,甚至应该,将一个类型为“{something} *”的变量传递给它;您应该将其传递给该类型的指针

在这种情况下,例如:

struct bpf_program *fp;
if((pcap_compile(pkt_handle, fp, str, 1, PCAP_NETMASK_UNKNOWN)==-1)

{

是错误的,并且

struct bpf_program pgm;
if((pcap_compile(pkt_handle, &pgm, str, 1, PCAP_NETMASK_UNKNOWN)==-1)

{

是正确的。

至于pcap_compile()之前的调用pcap_activate(),那是不正确的。您必须在调用调用它pcap_activate(),否则pcap_t它没有链接层标头类型,并且pcap_compile()不会知道它应该为其生成代码的链接层标头的类型。(我已经检查了对 libpcap 的修复,以禁止调用pcap_compile()尚未激活的pcap_t.)

于 2012-07-12T17:17:40.587 回答