将数据包强制转换为结构的Endian问题 [英] Endian issue with casting a packet to a struct
问题描述
我正在使用libtrace解析网络数据包,但我认为这是一个字节序问题.
I'm using libtrace to parse network packets but am having, what I think is, an endian issue.
这是Radiotap数据包的libtrace定义:
Here is the libtrace definition of a Radiotap packet:
typedef struct libtrace_radiotap_t {
uint8_t it_version; /**< Radiotap version */
uint8_t it_pad; /**< Padding for natural alignment */
uint16_t it_len; /**< Length in bytes of the entire Radiotap header */
uint32_t it_present; /**< Which Radiotap fields are present */
} PACKED libtrace_radiotap_t;
所以我将libtrace_packet_t
投射到此Radiotap结构并检查结果:
So I cast my libtrace_packet_t
to this Radiotap struct and check the results:
link = (char *) trace_get_packet_buffer(packet, &linktype, NULL);
if (linktype != TRACE_TYPE_80211_RADIO)
return;
rtap = (libtrace_radiotap_t *) link;
printf("%d %d %d %d\n", rtap->it_present, rtap->it_pad, rtap->it_len,
rtap->it_present);
在我的开发机器上(小端),pcap文件中的数据包中的Radiotap数据是:
On my development machine, which is little endian, the Radiotap data from the packets in my pcap file is:
806959 0 72 806959
这是正确的.我的开发机器已成功解析了我希望从pcap文件中看到的数据.
Which is correct. My development machine is successfully parsing the data I expect to see out of the pcap file.
在大字节序的生产环境中运行时,我看到不同的值:
When run on my production box, which is big endian, I see different values:
793775104 0 18432 793775104
同一pcap文件中的相同数据包.不同的Radiotap值.我怀疑问题出在两台机器的字节序不同.但是,rtap.it_version
是uint8_t
,它是一个字节,不应该受到字节序问题的影响吗?
Same packet within the same pcap file. Different Radiotap values. I suspect the issue is with the different endianness of the two machines. However, rtap.it_version
is a uint8_t
which, being single byte, shouldn't be affected by endian issues, no?
推荐答案
那应该是字节顺序问题. 对于72,十六进制为0x48,它是一个uint16_t,因此在不同的字节序中为0x4800 =18432.是的. 对于806959 = 0xC502F,在不同的字节序中为0x2F50C000 = 793775104.
That should be a endianness issue. For 72, the hex is 0x48, and it's a uint16_t, so in the different endianness that's 0x4800 = 18432. That's right. And for 806959 = 0xC502F, in the different endianness that's 0x2F50C000 = 793775104.
这可能有帮助:
#define T(x) (((x&0xff)<<24)|((x&0xff00)<<8)|((x&0xff0000)>>8)|((x&0xff000000)>>24))
这篇关于将数据包强制转换为结构的Endian问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!