大端模式与小端模式
1.存在情况:内存中的多字节数据相对于内存地址有大端和小端之分,磁盘文件中的多字节数据相对于文件中的偏移地址也有大端小端之分,而网络数据流同样有大端小端之分。
2.网络字节序:TCP/IP协议规定,网络数据流应采用大端字节序,即低地址位保存高位字节。
3.移植性:为使网络程序具有可移植性,使同样的C代码在大端和小端计算机上编译后都能正常运行,可以调用库函数做网络字节序和主机字节序的转换。因为此类函数在传入小端模式的数据时会自动转换为大端模式,而传入的大端模式的数据则不会被改变。
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
//Linux早期接口,只能处理IPV4,且为不可重入函数,不建议使用。
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
char *inet_ntoa(struct in_addr in);
h表示host,n表示network,l表示32位长整数,s表示16位短整数。