Richard
Richard

Reputation: 33

Why you don't need to use hton/ntoh functions for sending const char*?

I'm sending data buffer over the network using sockets. The only place I see usage of converting endianess is the port number of sender/receiver. I can understand that.

The thing I can't understand is that I’m sending a const char* (using send()/sendto(), depending on transfer protocol). As far as I understand, you transfer bytes over the network in Big Endian. The machine of mine is Little Endian.

What is the trick here of not using ntoh()/hton() functions when sending that const char*?

Upvotes: 0

Views: 242

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73171

Background: The concept of big-endian vs little-endian only applies to multi-byte integers (and floating point values); for historical reasons, different CPUs may represent the same numeric binary value in memory via different byte-orderings, and so the designers of the Berkeley sockets API created ntoh*() and hton*() to translate from the CPU's native byte-ordering (whatever that may be) to a "network-standard" format (they chose big-endian) and back, so that binary numbers can be transferred from one machine type to another without being misinterpreted by the recipient's CPU.

Crucially, this splintering of representations happens only above the byte-level; i.e. the ordering of bytes within an N-byte word may be different on different CPUs, but the ordering of bits within each byte is always the same.

A character string (as pointed to by a const char *) refers to a series of individual 8-bit bytes, and the bytes' ordering is interpreted the same way by all CPU types, so there is no need to convert their format to maintain data-compatibility across CPUs. (Note that there are different formats that can be used to represent character strings, e.g. ASCII vs UTF-8 vs UTF-16 vs etc, but that is a decision made by the software rather than a characteristic of the CPU hardware the software is running on; as such, the Berkeley sockets API doesn't try to address that issue)

Upvotes: 2

Related Questions