我想使用 htonl() 和 htos() 将消息从主机字节顺序转换为网络顺序。在这个消息中,有一些复杂的定义数据类型,如结构、枚举、联合和联合中的联合。
- 我是否必须对每个结构的成员和成员中的成员(包括多字节的联合成员)进行 htonl(s)?
- 对于一个工会,我可以只翻译最大的一个吗?
- 对于枚举,我可以把它翻译成很长吗?
- 我可以只编写一个使用 htonl(s) 发送和接收消息的函数吗?还是我必须想出另一个使用 ntohl(s) 来接收相同消息的方法?
结构
typedef struct {
unsigned short un1_s;
unsigned char un1_c;
union {
unsigned short un1_u_s;
unsigned long un1_u_l;
}u;
}UN1;
typedef struct {
unsigned short un2_s1;
unsigned short un2_s2;
} UN2;
typedef enum {
ONE,
TWO,
TRHEE,
FOUR
} ENUM_ID;
typedef struct {
unsigned short s_sid;
unsigned int i_sid;
unsigned char u_char;
ENUM_ID i_enum;
union {
UN1 un1;
UN2 un2;
} u;
} MSG;
代码
void msgTranslate (MSG* in_msg, MSG* out_msg){
/* ignore the code validating pointer ... */
*out_msg = *in_msg;
#ifdef LITLE_ENDIAN
/* translating messeage */
out_msg->s_sid = htons( in_msg->s_sid ); /* short */
out_msg->i_sid = htonl( in_msg->i_sid ); /* int */
/* Can I simply leave out_msg->u_char not to translate,
* because it is a single byte? */
out_msg->i_enum = htonl(in_msg->i_enum);
/* Can I simply translate a enum this way,? */
/* For an union whose 1st member is largest one in size than
* others, can I just translate the 1st one,
* leaving the others not to convert? */
out_msg->u.un1.un1_s = htons(in_msg->u.un1.un1_s);
/* for out_msg->u_char, can I simply leave it
* not to be converted, because it is a single byte? */
/* for an union whose 2nd member is largest one,
* can I just convert the 2nd one, leaving others
* not to be converted? */
out_msg->u.un1.u.un1_u_s = htos(in_msg->u.un1.u.un1_u_s ); /* short */
/* As above question, the following line can be removed?
* just because the u.un1.u.un2_u_i is smaller
* than u.un1.u.un1 in size ? */
out_msg->u.un1.u.un2_u_i = htol(in_msg->u.un1.u.un2_u_l ); /* long */
/* Since un1 is largest than un2, the coding translation un2 can be ignored? */
...
#endif
return;
}