您的位置:首页技术文章
文章详情页

linux - libpcap抓包结果不完整?

【字号: 日期:2024-07-03 18:58:02浏览:51作者:猪猪

问题描述

在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('%snn', 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(): %sn', 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个数据包:

linux - libpcap抓包结果不完整?

我的程序使用调试器看到的却是这样的,这个图对应上图第四个数据包(大小为474):

linux - libpcap抓包结果不完整?

为什么unsigned char * packet出现incomplete sequence?还有为什么tcp_data这么短?

是我代码里libpcap少了什么配置还是其他的原因?

还有一点补充是我访问其他网站时,偶尔能捕捉到完整的HTTP请求,但是在我访问的那个网页上就不行。

问题解答

回答1:

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

相关文章: