【发布时间】:2017-12-08 10:05:42
【问题描述】:
我正在使用 libpcap 编写一个小型分析工具,它可以嗅探以太网设备上的流量并对收到的数据包执行某种分析。为此,我有明显的 libpcap 循环:
void packet_loop(u_char *args, const struct pcap_pkthdr *header,
const u_char *packetdata) {
int size = (int)header->len;
//Before we map the buffer to the ethhdr struct,
//we check if the size fits
if (ETHER_HDR_LEN > size)
return;
const struct ethhdr *ethh = (const struct ethhdr *)(packetdata);
//If this protocol is IPv4 and the packet size is bigger than
//ETH hdr size
if (ETHERTYPE_IP == ntohs(ethh->h_proto)) {
//Before we map the buffer to the iph struct,
//we check if the size fits
if (ETHER_HDR_LEN + (int)sizeof(struct iphdr) > size)
return;
const struct iphdr *iph = (const struct iphdr*)
(packetdata + sizeof(struct ethhdr));
//If this protocol isn't UDP and the header length
//isn't 5 (20bytes)
if (IPPROTO_UDP != iph->protocol && 5 != iph->ihl)
return;
//eval_udp(packetdata, size);
const struct udphdr *udph = (const struct udphdr*)
(packetdata + sizeof(struct ethhdr) +
sizeof(struct iphdr));
if (DATA_SRCPORT == ntohs(udph->uh_sport) &&
DATA_DESTPORT == ntohs(udph->uh_dport)) {
analyse_data(packetdata);
}
}
}
调用在接收到特定数据包类型时截断的以下代码。如您所见,我使用静态变量来跟踪前一个数据包,以便比较两个数据包。
void analyse_data(const uint8_t *packet)
{
if (!packet)
return;
static const uint8_t *basepacket;
//If there was no packet to base our analysis on, we will wait for one
if (!basepacket) {
basepacket = packet;
return;
}
const struct dataheader *basedh = (const struct dataheader *)
(__OFFSETSHERE__ + basepacket);
const struct dataheader *dh = (const struct dataheader *)
(__OFFSETSHERE__ + packet);
printf("%d -> %d\n", ntohs(basedh->sequenceid),
ntohs(dh->sequenceid));
basepacket = packet;
return;
}
struct dataheader 是一个常规结构,就像etthdr。我希望有一个持续的打印输出,例如:
0 -> 1
1 -> 2
2 -> 3
不幸的是,我得到了不同的打印输出,这基本上是正确的。但大约每 20-40 个数据包,我会看到以下行为(示例):
12->13
13->14
0->15
15->16
...
有趣的是,当我只收到我所关注的特定类型的数据包 (8-10 Mbit/s) 时,这不会发生。尽管如此,只要我在“常规”网络环境(大约 100Mbit/s)中使用我的工具,我就会得到这种行为。我检查了我的 if 语句,它过滤了它完美工作的数据包(检查 UDP 源和目标端口)。 Wireshark 还向我显示,这些端口上没有一个数据包不属于该特定类型。
【问题讨论】:
-
很可能是由于您尚未粘贴的代码中存在一些未定义的行为。
-
嗯,出了点问题,这不是因为您在上面所做的简单比较和分配。
-
@TacoVox:你没有粘贴的部分包括整个程序的其余部分,而不仅仅是这个函数中的代码。一些错误可能会覆盖
basepacket。您甚至没有显示printf语句,因此我们看不到您打印的这些数字来自哪里。 (某些错误可能会更改数据包的序列号。)我们看不到nextpacket是什么。我们看不到这个程序是否是多线程的。你遗漏了重要的事情。 -
仍然不是一个完整的例子。您将一个指向
packet_loop()的指针传递给您将其保存到static值中,然后在以后的迭代中取消引用。packetdata指针指向哪里?在调用packet_loop()之间,该内存会发生什么变化。你已经把这一切都排除在外了。 -
@TacoVox 我实际上并没有忽略它。是的,你做到了。
标签: c network-programming libpcap