首頁  >  問答  >  主體

linux - libpcap抓包結果不完整?

在ubuntu14.04下使用libpcap抓包,我想得到一段使用http傳輸的html,但是得到的結果和同樣情況下wireshark獲得的數據不一致。

目前程式碼如下:

#include <pcap.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <string.h>
#include <netinet/in.h>

void getPacket(u_char * arg, const struct pcap_pkthdr * pkthdr, const u_char * packet)
{

    bpf_u_int32 caplen = pkthdr->caplen;
    bpf_u_int32 len = pkthdr->len;

    int * id = (int *)arg;

    struct iphdr *ip_header = (struct iphdr *)(packet + ETH_HLEN);
    struct tcphdr *tcp_header = (struct tcphdr *)(packet + ETH_HLEN + sizeof(struct iphdr));

    const u_char *tcp_data = packet + ETH_HLEN + sizeof(struct iphdr) + sizeof(struct tcphdr);

    printf("%s\n\n", tcp_data);
}

int main()
{
    char errBuf[PCAP_ERRBUF_SIZE];
    pcap_t * device = pcap_open_live("wlan0", 65535, 1, 0, errBuf);

    if(!device)
    {
        printf("错误: pcap_open_live(): %s\n", errBuf);
        exit(1);
    }

    struct bpf_program filter;
    pcap_compile(device, &filter, "tcp port 80 and host 123.206.7.47", 1, 0);
    pcap_setfilter(device, &filter);

    int id = 0;

    pcap_loop(device, -1, getPacket, (u_char*)&id);
    pcap_close(device);

    return 0;
}

伺服器有一個簡單的html,當我用瀏覽器存取伺服器http://123.206.7.47/test.html時,wireshark(同樣bpf)抓到這樣10個封包:

#我的程式使用偵錯器看到的卻是這樣的,這個圖對應上圖第四個資料包(大小為474):

#為什麼unsigned char * packet出現incomplete sequence?還有為什麼tcp_data這麼短?

是我程式碼裡libpcap少了什麼配置還是其他的原因?

還有一點補充是我造訪其他網站時,偶爾能捕捉到完整的HTTP請求,但是在我造訪的那個網頁上就不行。

伊谢尔伦伊谢尔伦2713 天前637

全部回覆(1)我來回復

  • 为情所困

    为情所困2017-05-16 13:26:16

    已經解決了。直接按caplen讀char就行了,printf("%s")输出不全似乎是因为某个二进制数据是被截斷。

    回覆
    0
  • 取消回覆