在Linux和Windows C语言网络编程时都需要用到htons和htonl函数,用来将主机字节顺序转换为网络字节顺序.,下面我们就来聊聊关于为什么网络编程时要考虑字节顺序?接下来我们就一起去了解一下吧!

为什么网络编程时要考虑字节顺序(字节序转换函数)

为什么网络编程时要考虑字节顺序

在Linux和Windows C语言网络编程时都需要用到htons和htonl函数,用来将主机字节顺序转换为网络字节顺序.

举例解释一下

在Intel主机中, 执行以下程序

int main() { printf("%d \n", htons(16)); return 0; }

得到的结果是4096,初一看感觉很怪。

解释如下:

数字16的16进制表示为0x0010,数字4096的16进制表示为0x1000。

由于Intel机器是小端,存储数字16时实际顺序为1000,存储4096时实际顺序为0010。因此在发送网络包时为了报文中数据为0010,需要经过htons进行字节转换。

如果用IBM等大端机器,则并不必须调用此字节顺序转换,但为了程序可移植性,还是最好用此函数转换一下。

另外需注意: 如果数字所占位数小于或等于一个字节, 不必用htons转换, 这是因为对于主机来说, 大小端的最小单位为字节。

顺便提一下

当然也有反过来的 将网络字节序转换为主机字节序 的函数: ntohl 和 ntohs

Linux man中相关内容

Name

htonl, htons, ntohl, ntohs - convert values between host and network byte order

Synopsis

#include <arpa/inet.h> uint32_t htonl(uint32_t hostlong); uint16_t htons(uint16_t hostshort); uint32_t ntohl(uint32_t netlong); uint16_t ntohs(uint16_t netshort);

Description

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.

The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.

On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.

Conforming to

POSIX.1-2001.

Some systems require the inclusion of <netinet/in.h> instead of <arpa/inet.h>.

,