c++ – Using htonl in the payload of a UDP packet

Question:

I am sent with winsock2 UDP packets of which the first 4 bytes of the payload are used to identify the packet.

Basic example:

uint32_t id= 1 //Esta valor ira incrementando
uint8_t* buffer =new uint8_t[1400];
((uint32_t*)buffer )[0] = id; //guardamos en los primeros 4 bytes el id del paquete
...
//añadimos el resto de datos  a buffer
//Enviamos el paquete por red

The doubt that I have:

Is it necessary to use htonl to convert the identifier before sending it?

Should I apply this transformation to the rest of the data (bytes) as well?

All the best.

Answer:

Is it necessary to use htonl to convert the identifier before sending it?
Should I apply this transformation to the rest of the data (bytes) as well?

It depends .

The payload is your sole responsibility. If you are absolutely and completely sure that the receiving machine uses the same endian and you have well defined (in both parts) the size of the data to read, it is not necessary.

Understand that this information is part of the OSI application layer . How you interpret it is the sole responsibility of your code.

You have many data exchange formats available that already take these things into account: And to some bad , you can even transmit your information as plain text , thus avoiding possible misinterpretations due to size / endian issues .

Scroll to Top