為什麼網絡編程時要考慮字節順序?在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>.
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!