struct ArpHeader
{
unsigned short hardwareType;
unsigned short protocolType;
unsigned char hardwareAddressLength;
unsigned char protocolAddressLength;
unsigned short operationCode;
unsigned char senderHardwareAddress[6];
unsigned char senderProtocolAddress[4];
unsigned char targetHardwareAddress[6];
unsigned char targetProtocolAddress[4];
};
这仅适用于硬件地址长度为6且协议地址长度为4的情况。地址长度也在头部中给出,因此要正确,结构应如下所示:
struct ArpHeader
{
unsigned short hardwareType;
unsigned short protocolType;
unsigned char hardwareAddressLength;
unsigned char protocolAddressLength;
unsigned short operationCode;
unsigned char senderHardwareAddress[hardwareAddressLength];
unsigned char senderProtocolAddress[protocolAddressLength];
unsigned char targetHardwareAddress[hardwareAddressLength];
unsigned char targetProtocolAddress[protocolAddressLength];
};
这显然行不通,因为地址长度在编译时是未知的。模板结构也不是一个选项,因为我想填写结构的值,然后只需将它从(ArpHeader*)转换为(char*),以获取可以发送到网络上的字节数组,或将接收到的字节数组从(char*)转换为(ArpHeader*)以解释它。
其中一种解决方案是创建一个类,拥有所有头字段作为成员变量,一个函数来创建表示ARP头的字节数组,该字节数组可以被发送到网络上,以及一个构造函数,该构造函数仅需要一个字节数组(在网络上接收)并通过读取所有头字段并将它们写入成员变量来解释它。但这不是一个好的解决方案,因为它需要更多的代码。
相反,对于UDP头的类似结构很简单,因为所有头字段都具有已知的恒定大小。
#pragma pack(push, 1)
#pragma pack(pop)
在结构声明周围添加代码,这样我就可以使用简单的C风格转换获取要发送到网络上的字节数组。
这里是否有任何解决方案可以接近结构或至少不需要比结构多很多的代码? 我知道结构中的最后一个字段(如果是数组)不需要特定的编译时大小,我能否在我的问题中使用类似的东西?只需将这4个数组的大小留空即可编译,但我不知道它实际上会如何运作。从逻辑上讲,它不能正常工作,因为如果第一个数组的大小未知,则编译器将无法确定第二个数组从哪里开始。
operator char*
和ArpHeader(char* data)
是否符合您的需求?您已经尝试过了吗?据我所知,这样实际底层结构变得无关紧要。 - Paweł Stawarz