主机字节序 & 网络字节序
什么是字节序
简单来说,就是数据在内存中的排列顺序,按照排列顺序的不同分为大端字节序(big endian)和小端字节序(little endian)
大端字节序
数据的高位字节存储在内存的低地址处,低位字节存储在内存的高地址处。
小端字节序
数据的高位字节存储在内存的高地址处,低位字节存储在内存的低地址处。
代码
#include<iostream>
using namespace std;
void byteorder()
{
union Test
{
short value;
char bytes[sizeof(short)];
};
Test test;
test.value = 0x0102;
if ((test.bytes[0] == 1) && test.bytes[1] == 2)
cout << "big endian" << endl;
else if ((test.bytes[0] == 2) && test.bytes[1] == 1)
cout << "little endian" << endl;
else
cout << "unknown..." << endl;
}
现代的大多数PC采用的是小端字节序,因此小端字节序又被称为主机字节序(host byte order)。
当数据在两台使用不同字节序的主机之间传递时,接收端接收数据就会发生错误,解决方案是:发送端总是把要发送的数据转变成大端字节序在发送,接收端在接收时根据自身采用的字节序决定是否要对数据进行转换。因此大端字节序也称为网络字节序(network byte order)
linux提供的字节序转换函数
#include<netinet/in.h>
uint32_t htonl(uint32_t hostlong); //converts the unsigned integer hostlong from host byte order to network byte order.
uint16_t htons(uint16_t hostshort);//converts the unsigned short integer hostshort from host byte order to network byte order.
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
长整型函数可以用来转换IP地址,短整型函数可以用来转换端口号。