Unix网络字节顺序及其判断


一:对于一个16字节的数据,比如0x0102,在内存中可以有两个方式来存贮。一种是0x0102,一种是0x0201,前者成为小段对其,后者成为大端对齐。

在网络编程中,需要考虑到网络数据的存储顺序问题,这是个很重要的问题。因为客户机的数据存储顺是不统一好的,比如Linux,Windows用的是小段对齐,BSD,AIX等Unix系统用的时大端对齐。如果要在不同容的许同上交换数据就必须考虑这个数据格式的问题。

在Linux/Unix中,通常的数据在堆中存储,堆的内存地址是有高到底编址的,这和栈的地址顺序相反。在硬件中,一般的地址顺序为,从右到左,递增。

所以,这个大小端可以,统一为左边为大端,右边为小端。

所以,小段对齐,即先存储小段数据,拿0x0102来说,的地址顺序为:0102,大端对齐的地址顺序为:0201.

下面有一个例子来判断大小断对齐:

  1. #include<stdio.h>   
  2. #include<unistd.h>   
  3. int byte_order(void);   
  4. int main(int argc,char *argv[])   
  5. {   
  6.     int val =0;   
  7.     val = byte_order();    
  8.     printf("%d\n",val);   
  9. }   
  10. int byte_order(void)   
  11. {   
  12.     int val;   
  13.     union  
  14.     {   
  15.         short s;   
  16.         char c[sizeof(short)];   
  17.     }un;   
  18.     un.s = 0x0102;   
  19.     if(sizeof(short) == 2)   
  20.     {   
  21.         if((un.c[0] == 1) && (un.c[1] == 2))   
  22.         {   
  23.             val = 1;/* big-endian */  
  24.         }   
  25.         else if((un.c[0] == 2) && (un.c[1] == 1))   
  26.         {   
  27.             val = 0;/*little-endian*/  
  28.         }   
  29.         else  
  30.         {   
  31.             val = 2;/* unknown */  
  32.         }   
  33.     }   
  34.     else  
  35.     {   
  36.         printf("sizeof(short) = %d\n"sizeof(short));   
  37.         val = -1;/*the size of short is not 1 byte,type nuknown.*/  
  38.     }   
  39.     return val;   
  40. }  

在gcc version 4.5.1 20100924 (Red Hat 4.5.1-4) (GCC)下结果为0:小段对齐。

二:在网络编程中,可以使用以下函数来转换网络顺序:

#include <netinet/in.h>
uint16_t htons(uint16_t host16bitvalue) ;
uint32_t htonl(uint32_t host32bitvalue) ;
Both return: value in network byte order
uint16_t ntohs(uint16_t net16bitvalue) ;
uint32_t ntohl(uint32_t net32bitvalue) ;
Both return: value in host byte order

n表示net(网络顺序),h表示host(本机顺序),s表示short,16bit;l表示long,32bit.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Harry_lyc/archive/2011/04/08/6310031.aspx

相关内容