C ++在套接字编程中的字节顺序 [英] C++ Byte order in socket programming

查看:167
本文介绍了C ++在套接字编程中的字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

支持我们发送以下数据

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

这也可以包装到struct。

This can also be wrapped into struct.

我的困惑在于 roll id ,我们可以使用 htons em>功能。但对于字符串 name ,我们应该如何做呢?我们需要使用任何这样的功能吗?它会工作在每一台机器,如mac,英特尔和其他网络?

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.

推荐答案

您可以使用 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.

这篇关于C ++在套接字编程中的字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆