2013-04-26 18 views
2

我的iOS的初學者,我的畢業設計是建立一種應用程序,可以在iOS上捕獲數據包。libpcap的iOS上的pcap_next()總是返回null

我使用libpcap的圖書館。我的iPhone是JB,我已經可以以root身份運行的應用程序。更具體地說,我可以得到我的net_interface:en0,但我無法捕獲任何數據包。pcap_next()總是返回null。

這是我的代碼:

-(IBAction)capture:(id)sender{ 
    char error_content[PCAP_ERRBUF_SIZE]; 
    char *net_interface=NULL; 
    net_interface=pcap_lookupdev(error_content); 
    NSString *devstr = [[NSString alloc] initWithUTF8String:net_interface]; 
    text1.text=devstr; 

    pcap_t *pcap_handle; 
    pcap_handle = pcap_open_live(net_interface, BUFSIZ, 0, 2, error_content); 

    struct pcap_pkthdr packet_capture; 
    const u_char *packet_flag; 
    packet_flag= pcap_next(pcap_handle, &packet_capture); 
    if (!packet_flag) { 
     [email protected]"capture failed"; 
    } 
    else{ 
     NSString *length =[[NSString alloc]initWithFormat:@"the length of packet is   %d",packet_capture.len]; 
     text2.text=length; 
     [length release]; 
    } 
     pcap_close(pcap_handle); 
    } 
@end 

如果有人對此有類似的記錄或不知道如何解決這個問題,我會更感激,如果你可以通過[email protected]與我聯繫。

+0

它解決了。我用它代替pcap_next.It工作,不錯的pcap_loop。 – 2013-04-26 08:06:15

回答

1
packet_flag= pcap_next(pcap_handle, &packet_capture); 
if (!packet_flag) { 
    [email protected]"capture failed"; 
} 

引述pcap_next()手冊頁:

pcap_next()返回一個指向成功的分組數據,並返回NULL,如果發生錯誤,或者如果沒有包被從現場看捕獲(如果,例如,他們被丟棄,因爲他們沒有通過數據包過濾器,或者,在支持啓動任何數據包到達之前讀超時平臺,超時到期的任何數據包到達之前,或者如果文件描述符因爲捕獲設備處於非阻塞模式,並且沒有數據包可供讀取),或者在「savefile」中沒有更多數據包可用。「不幸的是,無法確定是否發生錯誤。

iOS與OS X一樣,構建在衍生4.4-Lite的操作系統之上,並使用BPF; BPF是支持啓動的任何數據包到達之前讀超時數據包,給您指定2作爲超時參數pcap_open_live(),超時時間爲2個毫秒,因此,如果沒有數據包在2毫秒內到達你打電話pcap_next()pcap_next()後將返回NULL。

您通過使用pcap_loop()做出了正確的選擇。 pcap_next()不是一個非常好的API; pcap_next_ex()比較好,因爲是pcap_dispatch()pcap_loop()