套接字中的网络字节顺序 [英] Network Byte Order in sockets

查看:113
本文介绍了套接字中的网络字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c(Linux)中的套接字编程,我无法理解为什么在发送整数时需要使用htonl,而不是在发送字符串(char *)时。我已经阅读了很多论文,但我仍然不知道原因。

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.

推荐答案

这是因为通过网络发送的数据是以Big Endian命令发送。不同的平台以不同的顺序存储数据。

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

假设你有一个的0x9FD3。在Small Endian平台上,它将作为0xD39F存储在内存中。第一个字节是0xD3,下一个字节是0x9F。如果您将其发送到默认情况下使用Big Endian的计算机,它将被解释为0xD39F(54,1475),而不是0x9FD3(40,915)。另一方面,字符串保持为字符数组,这是为了开始。如果你有aString,它将被存储为a,S,t,r......在内存中,因为1个字符是1个字节宽。只有多个字节的数据类型将以相反的顺序存储在小端平台上,使转换毫无意义

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

这篇关于套接字中的网络字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆