我正在使用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还告诉我,那些端口上没有一个不是特定类型的数据包。
答案 0 :(得分:2)
libpcap控制它传递给packet_loop
的数据包数据。一旦packet_loop
返回,您无法保证分组数据的指针指向什么 - libpcap可能会丢弃数据包,或者它可以为新数据包重用相同的空间。
这意味着如果你想比较2个数据包,你必须复制1.数据包 - 你不能将指针从一个调用保存到packet_loop
并期望指针有效并指向相同的将来调用packet_loop
的数据包。所以你的代码可以改为例如。
void analyse_data(const uint8_t *packet, int size )
{
if (!packet)
return;
static const uint8_t basepacket[1024*64];
static int has_basepacket;
//If there was no packet to base our analysis on, we will wait for one
if (!has_basepacket){
if (size < sizeof basepacket) {
memcpy(basepacket, packet, size);
has_basepacket = 1;
}
return;
}
...
另外,请确保您在各处验证尺寸。仅仅因为以太网类型表明它是IPv4数据包,并不意味着您可以信任它包含完整的IP数据包。仅仅因为IP头表示它是20个字节,并不意味着你可以信任它包含一个完整的IP数据包,依此类推你尝试解码的所有层。