网络字节序和本地字节序号

网络字节序,一般是指采用大端法存储网络地址,

本地主机字节序,一般是指采用小端法存储本地主机地址.

大端法:低字节保存在内存的高位,高字节保存在内存的低位
小端法:低字节保存在内存的低位,高字节保存在内存的高位

UNIX网路编程-卷1:P64 LINE 4
术语“小端”和“大端”表示 多个字节值的哪一端(大端或小端)存储在该值的起始地址。

网络字节序和本地字节序号_第1张图片

uint32_t htonl(uint32_t hostlong);//本地字节序转网络字节序(用于IPV4地址)
uint16_t htons(uint16_t hostshort);//本地字节序转网络字节序(用于端口号)
uint32_t ntohl(uint32_t netlong);//网络字节序转本地字节序(用于IPV4地址)
uint16_t ntohs(uint16_t netshort);//网络字节序转本地字节序(用于端口号)

返回值都为数值类型
函数命名规则:
h[本地host]
to
n[网络network]
sshort类型2字节 对应端口号
llong类型4字节 对应IPV4地址

帮助文档

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.

数值类型–>字符串类型

 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
/*
 *af 指定协议族类型IPV4--> AF_INET IPV6 -->AF_INET6
 *src 结构体sockaddr_in中的sin_addr中的s_addr的地址
 * char * dst用于保存结果
 * dst 的长度
 */

将点分十进制的ip地址转换成数值格式

int inet_pton(int af, const char *src, void *dst);

总结

#include 
//本地字节序 --> 网络字节序 :地址 
uint32_t htonl(uint32_t hostlong);

//本地字节序 --> 网络字节序 :端口 uint16_t 
htons(uint16_t hostshort);

//网络字节序 --> 本地字节序 :地址 
uint32_t ntohl(uint32_t netlong);

//网络字节序 --> 本地字节序 :端口 
uint16_t ntohs(uint16_t netshort);

#include 
#include 
#include 
//本地字节序 --> 网络字节序 :地址 
int inet_aton(const char *cp, struct in_addr *inp); //字符串有效返回1 否则返回0

//本地字节序 --> 网络字节序 :地址 
in_addr_t inet_addr(const char *cp); //返回本地字节序的地址

//网络字节序 --> 本地字节序 :地址 
char *inet_ntoa(struct in_addr in); //返回本地字节序的点分十进制数串


#include 
#include 
#include 

//本地字节序 --> 网络字节序 :地址 
int inet_pton(int af, const char *src, void *dst);

//网络字节序 --> 本地字节序 :地址 
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);

你可能感兴趣的:(C/C++,网络字节序,本地主机字节序,大端法,小端法)