【发布时间】:2010-08-18 14:38:45
【问题描述】:
我已经编写了一个结构,它应该代表一个完整的 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*s 用于发送.
我的问题是,当我尝试在UDPPacket.verlen 之后分配任何内容时,它会向前跳过大约 5 个字节并从那里开始。例如,当我分配 iplen 字段时,不是将字节设置在偏移量 16 和 17,而是将它们分配在 23 和 24 之类的位置(我不能确切地说,因为我的程序在这里没有可用我的手机)。
是否有明显的原因导致我失踪了,或者我只是做错了什么?
【问题讨论】:
-
顺便说一句,我在 x64 Windows 7 上使用 Visual Studio 2008,但为 x86 编译。
标签: c++ visual-studio-2008 struct field byte