Windows Socket编程笔记之字节序及相关函数

字节序(Endianness):

    指多字节数据在计算机内存中或是网络传输中所使用的存储顺序.
    一般有大端(big-endian)小端(little-endian)两种顺序
    
    大端:地址的低位,存值的高位
    小端:地址的低位,存值的低位
    
    如下是一个32bit数0x0A0B0C0D采用大端和小端顺序存储的区别
    内存地址:    00  01  02  03
    大端表示:    0A  0B  0C  0D
    小端表示:    0D  0C  0B  0A    

主机字节序(Host Byte Order):

    主机字节序和本地主机的所使用的CPU有关,例如x86系列处理器采用的是小端(little-endian)顺序,而Motorola 6800采用的则是大端.
    想要确定自己的主机采用的是什么字节序存储数据,可用下面这段简单的C代码进行测试:

 1 // FileName: testing.c
 2 
 3 #include<stdio.h>
 4 void main()
 5 {
 6     unsigned int num = 0xaabbccdd;
 7     unsigned char *addr = &num;
 8     printf("%-9x %-9x %-9x %-9x\n", addr, addr+1, addr+2, addr+3);
 9     printf("%-9x %-9x %-9x %-9x\n", *addr, *(addr+1), *(addr+2), *(addr+3) );
10     
11     getchar();
12 }

网络字节序(Network Byte Order):

    网络字节序统一采用的是大端.


所以在网络编程中,需要把数据用统一格式表示,以便数据在不同的主机间进行传输时能被正确的理解.
而主机序又是不确定的,因此要进行必要的转换.以下是常用的转换函数.


htons : u_short类型主机(Host)序转为网络(Network)序.
htonl : Host    TO Network Long (u_long).
ntohs : Network To Host    Short(u_short).
ntohl : Network To Host    Long (u_long).

例如以下是MSDN中对htos函数的描述:
The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian).

u_short htons(
  u_short hostshort  
);
Parameters
    hostshort  [in] 16-bit number in host byte order.
Return Values
    The htons function returns the value in TCP/IP network byte order.
Remarks
The htons function takes a 16-bit number in host byte order and returns a 16-bit number in network byte order used in TCP/IP networks.


还有两个较长用的函数:
inet_ntoa : 将网络地址转换成以"."间隔的字符串地址(如192.168.1.1).
inet_addr : 将"数字+句点"的格式的IP地址转换到unsigned long中,返回值已经是按照网络字节顺序的
例如以下是MSDN中对inet_ntoa函数的描述:
The inet_ntoa function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.

char FAR * inet_ntoa(
  struct   in_addr in  
);
Parameters
in
[in] Structure that represents an Internet host address.
Return Values
If no error occurs, inet_ntoa returns a character pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.

Remarks
The inet_ntoa function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in ".'' (dot) notation as in "a.b.c.d.'' The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread—but no longer. Therefore, the data should be copied before another Windows Sockets call is made.

原文地址:https://www.cnblogs.com/rookie2/p/2705632.html