Sending an array of arbitrary length via a socket. Byte order

Now I am struggling with socket programming, and I am faced with a problem that I do not know how to solve in a portable way. The task is simple: I need to send an array of 16 bytes over the network, get it in the client application and analyze it. I know that there are functions like htonl, htons, etc. that can be used with uint16 and uint32. But what should I do with pieces of data more than this?

Thanks.

+2
source share
4 answers

You are talking an array of 16 bytes. It does not help. Endianness only matters for things big bytes.

If these are really raw bytes, then just send them, you will get them only the same

If this is really the structure you want to send,

struct msg { int foo; int bar; ..... 

Then you need to work through the buffer, pulling the desired values.

When sending, you need to collect the package in the standard order

  int off = 0; *(int*)&buff[off] = htonl(foo); off += sizeof(int); *(int*)&buff[off] = htonl(bar); ... 

When you receive

  int foo = ntohl((int)buff[off]); off += sizeof(int); int bar = ntohl((int)buff[off]); .... 

EDIT: I see that you want to send an IPv6 address, they are always in the network byte order, so you can just pass it raw.

+3
source

Endianness is a property of multibyte variables such as 16-bit and 32-bit integers. This is due to whether the first or low byte comes first. If the client application treats the array as separate bytes, it does not need to worry about the content, because the order of the bits in bytes is the same.

+3
source

htons , htonl etc. Designed to work with a single data item (for example, int) that exceeds one byte. An array of bytes, in which each of them is used as a separate data element (for example, a string), does not have to be translated between the host and the network byte order in general.

+1
source

The bytes themselves no longer indicate that any one byte transmitted by the computer will have the same value on the other receiving computer. Endianness is currently relevant for multibyte data types such as int.

In your particular case, it comes down to understanding what the recipient will do with your 16 bytes. If it will process each of the 16 entries in the array as separate single-byte values, you can simply send them without worrying about endiannes. If, on the other hand, the receiver considers an array of 16 bytes as four 32-bit integers, then you need to run each integer via hton () before sending.

Does it help?

+1
source

Source: https://habr.com/ru/post/1271075/


All Articles