网络中传输的数据必须使用网络字节序,即大端字节序
小端字节序(little-endian) - 低序字节存储在低地址 (主机字节序)
大端字节序(big-endian)- 高序字节存储在低地址 (网络字节序)
可以通过以下方法判断当前主机的字节序
#include<stdio.h>//指针强转
int main(int argc, char const *argv[])
{
int a=0x12345678;
char b;
b=(char)a;
printf("%#x %#x\n",a,b);
return 0;
}
#include<stdio.h>//数据类型强转
int main(int argc, char const *argv[])
{
int a=0x12345678;
printf("%#x %#x\n",(char)a,(short)a);
return 0;
}
#include <stdio.h>//共用体
union un {
int a;
short b;
char c;
};
int main(int argc, char const *argv[])
{
union un st;
st.a=0x12345678;
printf("%#x %#x\n",st.b,st.c);
return 0;
}
主机字节序到网络字节序转换
u_long htonl (u_long hostlong);
u_short htons (u_short short);
主机字节序到网络字节序转换
u_long ntohl (u_long hostlong);
u_short ntohs (u_short short);
IP地址转换
typedef uint32_t in_addr_t;
struct in_addr {
in_addr_t s_addr;
};
in_addr_t inet_addr(const char *cp); //从人看的ip地址转为机器使用的32位无符号整数
char *inet_ntoa(struct in_addr in); //从机器到人