Search code examples
csocketsintegersend

Network Byte Order in sockets


I'm learning sockets programming in c (Linux), and I can't really understand why is it necessary to use htonl when you are sending an integer, but not when you are sending a string (char*). I've read a lot of papers, but I still don't know why.


Solution

  • It's because data sent through networks are sent in Big Endian order. Different platforms store data in different orders.

    Say you have a short of 0x9FD3. On a Small Endian platform, it'll be stored in memory as 0xD39F. The first byte is 0xD3, and the next byte will be 0x9F. If you sent that to a machine that uses Big Endian by default, it'll be interpreted as 0xD39F (54,1475), as opposed to 0x9FD3 (40,915). Strings on the other hand, are kept as arrays of chars, which is in order to begin with. If you had "aString", it would be stored as 'a', 'S', 't', 'r'... in memory because 1 char is 1 byte wide. Only data types of multiple bytes will be stored in reverse order on small endian platforms, making the conversion pointless