27. 什么是网络字节序? 函数实现 htons 和 htonl

网络字节序:网络字节顺序是 TCP/IP 中规定好的一种数据表示格式,它与具体的 CPU 类型、操作系统等无关,从而可以保证数据在不同主机之间传输时能够被正确解释。在网络字节序中,数据的高位字节存储在低地址,而低位字节存储在高地址。这是因为网络传输通常使用大端字节序(Big-Endian),即最高有效字节先传输。网络字节顺序采用 **big endian(大端)**排序方式。uint32_t htonl(uint32_t hostlong);uint16_t htons(uint16_t hostshort);uint32_t ntohl(uint32_t netlong);uint16_t ntohs(uint16_t netshort);h 表示 host,n 表示 network,l 表示 32 位长整数,s 表示 16 位短整数。如果主机是小端字节序,这些函数将参数做相应的大小端转换然后返回,如果主机是大端字节序,这些函数不做转换,将参数原封不动地返回。#include <stdio.h>typedef unsigned short int uint16;typedef unsigned long int uint32;// 短整型大小端互换#define BigLittleSwap16(A) ((((uint16)(A) & 0xff00) >> 8) | \ (((uint16)(A) & 0x00ff) << 8))// 长整型大小端互换#define BigLittleSwap32(A) ((((uint32)(A) & 0xff000000) >> 24) | \ (((uint32)(A) & 0x00ff0000) >> 8) | \ (((uint32)(A) & 0x0000ff00) << 8) | \ (((uint32)(A) & 0x000000ff) << 24))// 本机大端返回1,小端返回0int checkCPUendian(){ union{//定义 枚举变量 unsigned long int i; unsigned char s[4]; }c; c.i = 0x12345678; return (0x12 == c.s[0]);}// 模拟htonl函数,本机字节序转网络字节序unsigned long int t_htonl(unsigned long int h){ // 若本机为大端,与网络字节序同,直接返回 // 若本机为小端,转换成大端再返回 return checkCPUendian() ? h : BigLittleSwap32(h);}// 模拟ntohl函数,网络字节序转本机字节序unsigned long int t_ntohl(unsigned long int n){ // 若本机为大端,与网络字节序同,直接返回 // 若本机为小端,网络数据转换成小端再返回 return checkCPUendian() ? n : BigLittleSwap32(n);}// 模拟htons函数,本机字节序转网络字节序unsigned short int t_htons(unsigned short int h){ // 若本机为大端,与网络字节序同,直接返回 // 若本机为小端,转换成大端再返回 return checkCPUendian() ? h : BigLittleSwap16(h);}// 模拟ntohs函数,网络字节序转本机字节序unsigned short int t_ntohs(unsigned short int n){ // 若本机为大端,与网络字节序同,直接返回 // 若本机为小端,网络数据转换成小端再返回 return checkCPUendian() ? n : BigLittleSwap16(n);}

发表评论