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

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

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

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

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

  • htons: h代表host主机, to就是to, n代表net网络, s是unsigned short无符号短整型(32位系统中是2字节)
  • htonl: h和to和n 同上, l是unsigned long无符号长整型(32位系统中是4字节)
举例解释一下

在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>.

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页