5
cout << "Hello World !" << endl;

For my very first post on stackoverflow: When are we supposed to use the htonl function? I have gone through the man page. However, I don't really understand when and how to use it.

jxh
  • 64,506
  • 7
  • 96
  • 165
json27
  • 69
  • 1
  • 1
  • 5
  • 2
    Whenever you are sending a 4 byte value to a different machine. The receiving machine then uses `ntohl` to recover the value. – jxh May 22 '15 at 01:02
  • You need it only if you are doing network programming or sharing binary data between different computer architectures. There's the corollary function `ntohl`, which is actually the [same function](http://stackoverflow.com/questions/11617684/when-is-htonlx-ntohlx-or-when-is-converting-to-and-from-network-byte-o) as htonl on the same platform.. There's also `htons` and `ntohs` for 2-byte values. – selbie May 22 '15 at 01:06
  • It is worth mentioning, many modern applications transmit data textually, such as with XML over HTTP. But, lower level programming will deliver data in binary, and the world of computing is still heterogeneous. – jxh May 22 '15 at 03:17
  • Thank you for all the useful information ! – json27 May 22 '15 at 07:19

1 Answers1

7

Host TO Network translation. It makes sure the endian of a 32 bit data value is correct (Big endian) for network transport. ntohl -- Network TO Host -- is used by the receiver to ensure that the endian is correct for the receiver's CPU. Keep an eye out for htons and ntohs for handling 16 bits, and out there somewhere are likely htonll and ntohll for 64 bits.

Using all of them is as simple as pass in the number you want converted and out comes the converted number. You may find that absolutely nothing has happened on some processors because their endian is already big.

uint32_t inval = 0xAABBCCDD;
uint32_t outval = htonl(inval);

Will, on most desktop hardware, result in outval being set to 0xDDCCBBAA

user4581301
  • 29,019
  • 5
  • 26
  • 45