C++ Byte order in socket programming

2019-01-28 09:23发布

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.

3条回答
smile是对你的礼貌
2楼-- · 2019-01-28 10:02

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.

查看更多
男人必须洒脱
3楼-- · 2019-01-28 10:10

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.

查看更多
Viruses.
4楼-- · 2019-01-28 10:17

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.

查看更多
登录 后发表回答