2012-07-12 16 views
0

我寫使用「WLAN」界面上的libpcap庫pcaket嗅探程序。我想過濾捕獲的數據包,以便只處理Beacon幀。所以,我寫了下面的代碼:
使用pcap_compile()表達

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 

所以,可能是什麼問題呢?

Opearting操作系統:Ubuntu 10.10

更新:

我之前pcap_activate()語句移動使用pcap_compile()語句。該程序工作正常,只捕獲信標幀。但是,仍然pcap_compile()似乎返回-1,並在輸出中得到以下語句:

Compile: 802.11 link-layer types supported only on 802.11 

可能是什麼問題?我正在使用Netgear USB無線網卡。
UPDATE2:

至於建議的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把手指向了正確的接口。但我仍然收到錯誤信息。

+0

對不起,我的錯誤。我實際上在pcap_activate()語句之後使用了pcap_compile(),這是錯誤的。在pcap_compile()之前移動pcap_compile()部分代碼,程序工作正常。 – bengaluriga 2012-07-12 09:22:58

+0

你還需要使'fp'指向某個東西。如果這裏的代碼在沒有'fp'被初始化的情況下工作,那只是純粹的運氣。 – nos 2012-07-12 10:06:59

+0

@nos我mapced記憶fp(看看更新2的帖子)。但問題仍然存在。 – bengaluriga 2012-07-12 11:04:34

回答

2

崩潰,如上所述,是因爲FP並沒有指向的東西。如果一個函數具有類型「{}東西*」的說法,這並不意味着你需要,甚至應該,它傳遞類型的變量「{}東西*」;你應該通過它的指針該類型。

在這種情況下,例如:

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_activate()之前致電pcap_compile(),這是不正確的。您必須在之後調用,調用pcap_activate(),否則pcap_t不具有鏈路層報頭類型,並且pcap_compile()將不知道應該爲其生成代碼的鏈路層報頭的類型。 (我已經檢查了libpcap的一個修復程序,禁止在尚未激活的pcap_t上調用pcap_compile()。)

+0

您是對的。謝謝。它現在工作完美。 – bengaluriga 2012-07-13 06:26:18