我正在尝试在C中创建IP标头。
typedef struct header
{
//IP-Header
unsigned char ip_v:4, ip_hl:4;/* this means that each member is 4 bits */
unsigned char ip_tos; //1 Byte
unsigned short int ip_len; //2 Byte
unsigned short int ip_id; //2 Byte
unsigned short int ip_off; //2 Byte
unsigned char ip_ttl; //1 Byte
unsigned char ip_p; //1 Byte
unsigned short int ip_sum; //2 Byte
unsigned int ip_src; //4 Byte
unsigned int ip_dst; //4 Byte
} __attribute__((packed)) ipheader;
现在,我想使用struct并将十六进制值保存在变量中。
int main()
{
ipheader iph;
iph.ip_v='\x4';
iph.ip_hl='\x5';
iph.ip_tos='\x00';
return 0;
}
如何将103C写入iph.ip_len?而且这种结构是存储IP标头的好方法吗?
如何使用iphdr结构?
除此之外,您还应谨慎对待字节序(请参见ntohl和htonl函数),具体取决于您要对其中的数据进行处理(不说)。另请参见为什么字节顺序在字节中的重要性在字节之间?关于iphdr的偏执。
为了编写值本身,您可以使用所使用的标准/编译器允许的任何格式,例如,如果您使用带有适当标志,八进制或十进制或字符数组的正确GCC版本,则使用二进制文字。
以下是不同文字格式的一些示例:
十六进制: 0x103C
字符数组:(char *){ 10, 60 }
或(char *){ 10, '<' }
八进制: 010074
二进制: 0b1000000111100
如果您不希望在不同类型之间移动值或对它们进行一些时髦的数学运算,则您甚至不需要强制转换-否则编译器会将值解释为int
可能对您造成问题的原因,尤其是因为不同的签名。在这种情况下,只需添加前缀(uint16_t)
或您需要的任何前缀(您应该使用系统中定义的相同类型-参见答案顶部的有关iphdr的建议-或固定长度的定义,以避免可移植性问题或将来的更新问题)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句