Network Byte Order in sockets

♀尐吖头ヾ 提交于 2020-01-06 02:39:23

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28253786/network-byte-order-in-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!