C++套接字编程中的字节顺序

发布于 2024-11-18 00:31:03 字数 439 浏览 4 评论 0原文

在 C++ 中,我们使用网络上的套接字发送数据。我知道我们需要使用 htons()ntohs() 函数来维护字节顺序 big endianlittle endian< /强>。

支持我们有以下要发送的数据

int roll;
int id;
char name[100];

这也可以包装到结构中。

我的困惑是,对于 rollid,我们可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

握住你手 2024-11-25 00:31:03

您可以将 htonl 用于 int,而不是 htons

该名称不需要重新排序,因为数组的字节直接对应于网络上的字节。

字节顺序问题仅在大于字节的字时出现,因为不同的体系结构选择不同的端来放置最低有效字节。

You'd use htonl for int, not htons.

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.

无力看清 2024-11-25 00:31:03

对于 char 数组,这种转换不是必需的,因为它们没有网络字节顺序,而是按顺序传输。 ntohshtons 存在的原因是某些数据类型由较少和较高的有效位组成,这些位在不同的体系结构上有不同的解释。字符串中并非如此。

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 and htons 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.

苍白女子 2024-11-25 00:31:03

要在此处添加有用的注释 - 如果您的结构变得更加复杂,您最好考虑像 Boost.SerializationGoogle 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 using htons) before the string itself, don't just send 100 chars every time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文