tft每日頭條

 > 科技

 > 為什麼網絡編程時要考慮字節順序

為什麼網絡編程時要考慮字節順序

科技 更新时间:2024-09-10 03:21:38

為什麼網絡編程時要考慮字節順序?在Linux和Windows C語言網絡編程時都需要用到htons和htonl函數,用來将主機字節順序轉換為網絡字節順序.,下面我們就來聊聊關于為什麼網絡編程時要考慮字節順序?接下來我們就一起去了解一下吧!

為什麼網絡編程時要考慮字節順序(字節序轉換函數)1

為什麼網絡編程時要考慮字節順序

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

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关科技资讯推荐

热门科技资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved