【发布时间】:2014-06-02 13:00:47
【问题描述】:
我正在使用现有代码,通过 TCP 连接传递数据 - union ibv_gid 而不转换字节序。里面有评论:"The gid will be transfer byte by byte so no need to do "hton"。代码是正确的并且有效,但我不明白为什么数据是逐字节传递的(实际上它们传递了整个结构)以及为什么不需要字节序转换。他们传递的数据类型是:
union ibv_gid {
uint8_t raw[16];
struct {
uint64_t subnet_prefix;
uint64_t interface_id;
} global;
};
** 对于其他数据类型(如 int 等),它们确实会转换前后的数据
//VL_sock_sync_data function synchronizes between the two sides
//by exchanging data between the two sides.
//size bytes are being copied from out_buf to the other side, and being saved in in_buf.
rc = VL_sock_sync_data(sock_p, sizeof(union ibv_gid), &local_gid, &tmp_gid);
你能解释一下为什么不需要字节序转换吗? 感谢您的帮助
【问题讨论】:
-
如果两个对等主机具有相同的字节序,结构成员对齐规则,成员间填充!成员大小和整体结构大小,按位复制就足够了。由于其中许多参数取决于编译器、编译器版本、使用的编译器标志以及周围的#pragmas,因此您可以看到将结构用作网络协议确实非常危险。