我正在尝试使用 WinPCap 获取和解析以太网标签(目标地址、源地址、类型/长度字段)。
我主要是从 WinPCap SDK 复制/粘贴。我正在尝试将 WinPCap 数据包数据(在 pkt_data 中)存储在名为 ethernet 的结构中,该结构包含目标地址 [6 字节]、源地址 [6 字节]、类型/长度字段(短整型)和数据包长度(整型)。
我认为 pkt_data 的前 6 个字节是目标地址,接下来的 6 个字节是源地址,后面的两个字节是类型/长度字段,但我不确定。
有谁知道这个例子中 WinPCap 存储的标签的确切字节顺序?
/* If device is open, acquire attributes from packet */
if( ( res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
{
if(res != 0)
{
/* Acquire the length of the capture */
ethernet->length = header->caplen;
/* Acquire destination MAC address */
for (i = 0; i < 6; i++)
ethernet->destAddress[i] = pkt_data[i];
/* Acquire source MAC address */
for ( i = 6; i < 12; i++ )
ethernet->srcAddress[i] = pkt_data[i];
/* Acquire etherType type/length designation field */
ethernet->type = ( pkt_data[12] | pkt_data[13] );
/* Acquire the remaining data of the packet */
for ( i = 14; (i < header->caplen + 1); i++ )
ethernet->data[i - 14] = pkt_data[i];
}
/* Device error: cannot read from packet */
else if(res == -1)
printf("Error reading the packets: %s\n", pcap_geterr(fp));
}
最佳答案
libpcap/WinPcap抓包中数据的字节顺序就是数据在网络上传输的字节顺序; libpcap/WinPcap 提供原始数据包数据(“伪 header ”信息除外,例如 Radiotap radio header ,它们不会出现在线路上,并且以生成它们的软件使用的任何字节顺序排列,例如小端字节序) Radiotap)。
最好将 MAC 地址视为 6 字节序列,而不是 48 位数字,因此它们不存在字节顺序问题。目的地址在前,所以在pkt_data[0]
到pkt_data[5]
;接下来是源地址,因此它在 pkt_data[6]
到 pkt_data[11]
中。
注意
/* Acquire source MAC address */
for ( i = 6; i < 12; i++ )
ethernet->srcAddress[i] = pkt_data[i];
是错误的 - srcAddress
可能是一个 6 字节数组,所以它有 srcAddress[0]
到 srcAddress[5]
,并且没有打开 srcAddress[6]
。你可以用
/* Acquire source MAC address */
for ( i = 0; i < 6; i++ )
ethernet->srcAddress[i] = pkt_data[i + 6];
但使用 memcpy()
复制数据可能比自己编写循环更简单:
memcpy(ethernet->dstAddress, &pkt_data[0], 6);
memcpy(ethernet->srcAddress, &pkt_data[6], 6);
type/length 字段紧随其后,长度为两个字节,因此位于 pkt_data[12]
和 pkt_data[13]
中。根据 the IEEE 802.3 standard ,“长度/类型字段首先以高位八位字节发送和接收。” “第一个”八位位组是pkt_data[12]
,所以它是“高位八位位组”,它应该在值的高位 8 位; “第二个”八位字节是 pkt_data[13]
并且在值的低 8 位中,所以
ethernet->type = (pkt_data[12]<<8) | pkt_data[13];
关于c - 如何使用 WinPCap 获取以太网标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12844229/