gpt4 book ai didi

c - 为什么 libpcap 函数捕获的数据包的以太网和 ip header 失真

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:27 25 4
gpt4 key购买 nike

我使用 libpcap 函数 pcap_next() 从其他主机捕获一些 tcp 数据包我检查了捕获的数据包的字节并注意到数据包的以太网和 ip header 失真,乱七八糟,有很多 0但 TCP header 没问题

这可能是什么原因?

代码:

pcap_t* create_pcap_handler()
{
pcap_t *handle; /* Session handle */
char *dev; /* The device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
struct bpf_program fp; /* The compiled filter */
char filter_exp[] = "port 32000"; /* The filter expression */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP subnet*/

/* Define the device */
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
exit(2);
}
/* Find the properties for the device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
net = 0;
mask = 0;
}

struct in_addr tmp;
tmp.s_addr=net;
char IPdotdec[20];
inet_ntop(AF_INET, (void *)&tmp, IPdotdec, 16);
printf("net is %s\n", IPdotdec);
tmp.s_addr=mask;
inet_ntop(AF_INET, (void *)&tmp, IPdotdec, 16);
printf("mask is %s\n", IPdotdec);
printf("dev is %s\n",dev);

handle = pcap_open_live(dev, BUFSIZ, 0, 0, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
exit(2) ;
}
/* Compile and apply the filter */
if (pcap_compile(handle, &fp, filter_exp, 0, mask) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
exit(2);
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
exit(2);
}

return handle;
}

和主要功能

int main()
{
pcap_t * pcap_handler=create_pcap_handler();
struct pcap_pkthdr pcap_header; /* The header that pcap gives us */
const u_char *pcap_packet; /* The actual packet */
pcap_packet = pcap_next(pcap_handler, &pcap_header);
if(pcap_packet !=NULL)
printf("capture one packet with length of %d\n", pcap_header.len);
pcap_close(pcap_handler);


return 0;
}

最佳答案

pcap_packet = pcap_next(pcap_handler, &pcap_header);
if(pcap_packet !=NULL)
printf("capture one packet with length of %d\n", pcap_header.len);
pcap_close(pcap_handler);
parse_pkt(pcap_packet,pcap_header.len);

那是行不通的。

当您关闭 pcap_handler 时,无法保证调用 pcap_next()pcap_next_ex() 返回的任何指针 pcap_handler 将继续有效。

尝试

pcap_packet = pcap_next(pcap_handler, &pcap_header);
if(pcap_packet !=NULL)
printf("capture one packet with length of %d\n", pcap_header.len);
parse_pkt(pcap_packet,pcap_header.len);
pcap_close(pcap_handler);

相反。

关于c - 为什么 libpcap 函数捕获的数据包的以太网和 ip header 失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com