gpt4 book ai didi

c++ - 结构中的字段跳过字节

转载 作者:太空狗 更新时间:2023-10-29 21:08:16 24 4
gpt4 key购买 nike

我有一个我写的结构,它应该代表一个完整的 UDP 数据包,带有以太网头和所有。在这里:

#pragma pack(1)
struct UDPPacket {
// an array to hold the destination mac address of the packet
unsigned char dstmac[6];

// an array to hold the source mac address of the packet
unsigned char srcmac[6];

// two bytes to hold the packet type, this is almost always IP (08 00)
WORD ethtype;

// each of the subfields of this take up 4 bits. ver, the first half,
// is the ip version, which should usually be 4 for ipv4, and the second
// is the length of the header divided by 4, which is almost always 5
struct {
unsigned ver : 4;
unsigned len : 4;
} verlen;

// this isn't used in ipv4 and is 0
BYTE tos;

// the total length of the header + data
WORD iplen;

// the id of this datagram for reassembling fragmented packets
WORD id;

// the first subfield occupies 3 bits and is the flags of this packet, which is usually 0
// the second subfield is the fragmentation offset for large datagrams that have been split up for sending, usually 0
struct {
unsigned flags : 3;
unsigned fragmentation : 13;
} flagfrag;

// time to live; usually 35 or 128
BYTE ttl;

// the protocol with which this packet is being transported
// 1 = ICMP, 2 = IGMP, 6 = TCP, 17 = UDP
BYTE protocol;

// the ip checksum of this packet
WORD ipchecksum;

// the source ip of this packet
DWORD src;

// the destination ip of this packet
DWORD dest;
// the port from which this packet is coming
WORD srcport;

// the port this packet is headed to
WORD destport;

// the length of the udp header + data, not including the ip header
// so it's usually basically iplen - 20
WORD udplen;

// the udp checksum of this packet
WORD udpchecksum;

// a char pointer to the data of the packet
unsigned char data[10000];
};
#pragma pack()

当然,这是一个真正的 UDP 数据包的表示,字节必须与它们在数据包中的偏移量相同,并且指向这种类型的结构的指针将被转换为 unsigned char* 用于发送。
我的问题是,当我尝试在 UDPPacket.verlen 之后分配任何内容时,它会向前跳过大约 5 个字节并从那里开始。例如,当我分配 iplen 字段时,不是将字节设置在偏移量 16 和 17 处,而是将它们分配在 23 和 24 之类的位置(我不能准确地说,因为我没有我的程序在我的手机上可用)。
是否有明显的原因导致我遗漏了这一点,或者我只是做错了什么?

最佳答案

您的#pragmas 看起来是正确的。位域不会“自动打包”为适合明确指定的位数的最小类型。我怀疑 verlen 正在采用您给定的类型“unsigned”并假设它是一个大小为 unsigned int 的 bitfiend,这在您的编译器中听起来像是 32 位。尝试将 verlen 的字段改为“unsigned char”。

更多在这里。此处指定“unsigned char”的能力是 MSFT 扩展(对 ANSI C),但应该有效:http://msdn.microsoft.com/en-us/library/yszfawxh(VS.80).aspx

注意flagfrag 也一样,应该是“unsigned short”。

关于c++ - 结构中的字段跳过字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513239/

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