Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Byte order in socket programming

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.

like image 665
Vijay Avatar asked Feb 24 '23 17:02

Vijay


2 Answers

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.

like image 160
Marcelo Cantos Avatar answered Mar 06 '23 03:03

Marcelo Cantos


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.

like image 25
Constantinius Avatar answered Mar 06 '23 04:03

Constantinius