網路序與主機序
摘要:
用一個例子演示htons的用法,用於編譯的centos虛擬機器為小端模式,因此下面的程式輸出為
10 00
4096
與htons函式類似的幾個函式及對應的作用如下:
uint3...
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.
/*************************************************************************\ *Copyright (C) 52coder, 2018. * * 本例演示函式htons,解釋資料在底層的儲存。主體程式來自於深入理解計算機系統 * 程式碼中使用typedef將資料型別byte_pointer定義為一個指向型別為unsigned char的物件的指標, * 這樣一個位元組指標引用一個位元組序列,其中每個位元組都被認為是一個非負整數。 * htons用於將主機位元組序轉換為網路位元組序,該例子能清晰說明轉變過程。 \*************************************************************************/ #include <stdio.h> typedef unsigned char * byte_pointer; void show_bytes(byte_pointer start,size_t len) { size_t i; for(i = 0 ;i < len;i++) { printf(" %.2x",start[i]); } printf("\n"); } void show_short(short x) { show_bytes((byte_pointer)&x,sizeof(x)); } void show_int(int x) { show_bytes((byte_pointer)&x, sizeof(x)); } void show_float(int x) { show_bytes((byte_pointer)&x, sizeof(x)); } void show_pointer(void *x) { show_bytes((byte_pointer)&x, sizeof(x)); } void test_show_bytes(int val) { int ival = val; float fval = (float)ival; int *pval = &ival; show_short(ival); } int main() { short int x = 16; test_show_bytes(x); printf("%d\n",htons(x)); return 0; }