C++套接字编程中的字节顺序
在 C++ 中,我们使用网络上的套接字发送数据。我知道我们需要使用 htons() 、 ntohs() 函数来维护字节顺序 big endian 和 little endian< /强>。
支持我们有以下要发送的数据
int roll;
int id;
char name[100];
这也可以包装到结构中。
我的困惑是,对于 roll 和 id,我们可以使用 htons() 函数。但是对于字符串name,我们应该做什么以及如何做呢?我们需要使用这样的功能吗?它可以在 Mac、intel 和其他网络等每台机器上运行吗?
我想在一个数据包中发送所有三个字段。
In C++ we send data using socket on the network. I am aware that we need to use htons() , ntohs() function to maintain byte order big endian and little endian.
support we have following data to be sent
int roll;
int id;
char name[100];
This can also be wrapped into struct.
My confusion here is, for roll and id, we can use htons() function. But for the string name, what should and how should we do it? Do we need to use any such function? will it work on every machine like mac, intel and other network?
I want to send all three fields in one packet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将
htonl
用于int
,而不是htons
。该名称不需要重新排序,因为数组的字节直接对应于网络上的字节。
字节顺序问题仅在大于字节的字时出现,因为不同的体系结构选择不同的端来放置最低有效字节。
You'd use
htonl
forint
, nothtons
.The name doesn't need to be reordered, since the bytes of the array correspond directly to bytes on the network.
The issue of byte-order only arises with words larger than a byte, since different architectures choose different ends at which to place the least-significant byte.
对于 char 数组,这种转换不是必需的,因为它们没有网络字节顺序,而是按顺序传输。
ntohs
和htons
存在的原因是某些数据类型由较少和较高的有效位组成,这些位在不同的体系结构上有不同的解释。字符串中并非如此。For char arrays this conversion is not necessary since they do not have a network byte order but are sequentially transmitted. The reason that
ntohs
andhtons
exist, is that some data types consist of lesser and more significant bits, which are interpreted differently on different architectures. This is not the case in strings.要在此处添加有用的注释 - 如果您的结构变得更加复杂,您最好考虑像 Boost.Serialization 或 Google Protocol Buffers,它在幕后为您处理字节序。
对字符串进行编码时,请确保在字符串本身之前发送一个长度(可能是使用
htons
处理的short
),不要每次只发送 100 个字符。To add to helpful comments here - if your structs get much more complex you could be better off considering a serialization library like Boost.Serialization or Google Protocol Buffers, which handle endianness for you under the covers.
When encoding the string, make sure you send a length (probably a
short
handled usinghtons
) before the string itself, don't just send 100 chars every time.