linux - libpcap抓包结果不完整?

查看:170
本文介绍了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请求,但是在我访问的那个网页上就不行。

这个问题已被关闭,原因:问题已解决 - 问题已解决,且对他人无借鉴意义

解决方案

已经解决了。直接按caplen读char就行了,printf("%s")输出不全似乎是因为某个二进制数据是\0被截断。

这篇关于linux - libpcap抓包结果不完整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆