【问题标题】:Libpcap does not capture whole packetLibpcap 不捕获整个数据包
【发布时间】:2012-09-29 01:14:39
【问题描述】:

我正在尝试使用libpcap 捕获数据包。这是我的代码:

int main (int argc, char **argv) {
    char *dev = "eth0";
    char errbuf[PCAP_BUFFER_SIZE];
    pcap_t *handle;

    char filter[] = "tcp and src port 80";
    struct bpf_program fp;
    bpf_u_int32 mask, net;

    handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
    pcap_compile(handle, &fp, filter,0,net);
    pcap_setfilter(handle, &fp);
    pcap_loop(handle, -1, got_packet, NULL);

    pcap_freecode(&fp);
    pcap_close(handle);

    return 0;
}

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
    static int count = 1;
    static int http_count = 1;
    const struct sniff_ethernet *ethernet;
    const struct sniff_ip *ip;
    const struct sniff_tcp *tcp;

    int size_ip;
    int size_tcp;
    int size_payload;

    count++;

    ethernet = (struct sniff_ethernet*) (packet);
    ip = (struct sniff_ip*) (packet + SIZE_ETHERNET);
    size_ip = IP_HL(ip)*4;
    if (size_ip  < 20){
        printf("Invalid IP header %d", size_ip);
        return;
    }

    if (ip->ip_p != IPPROTO_TCP){
        printf("Not TCP\n");
        return;
    }

    tcp = (struct sniff_tcp*) (packet +SIZE_ETHERNET+size_ip);
    size_tcp = TH_OFF(tcp) * 4;
    if (size_tcp < 20) {
        printf("Invalid TCP header");
        return;
    }

    if ((tcp->th_flags & TH_ACK) != 0) {
        const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp);
        size_payload = ntohs(ip->ip_len)- (size_ip + size_tcp);
        std::cout << payload << "\n";       
        if (count == 4)
            exit(0);
    }

参数为:

#define SNAP_LEN    65535
#define SIZE_ETHERNET   14
#define ETHER_ADDR_LEN  6
#define PCAP_BUFFER_SIZE 65535

现在,整个第四个数据包都没有打印出来。我使用tcpdump 转储了数据包,它得到了整个数据包,但我的代码没有。这里有什么问题吗?

【问题讨论】:

    标签: networking network-programming network-protocols libpcap


    【解决方案1】:

    事实证明这是打印的问题。我使用了函数print_payload,现在可以正常使用了。

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 2014-03-12
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多