判断主机、网络字节序和互相转换
大端字节序(big-endian):按照内存地址的增长方向,高位数据储存于低位地址。
小端字节序(little-endian):按照内存地址增长方向,高位数据储存于高位地址。
判断主机、网络字节序:
#include <stdio.h>
#include <arpa/inet.h> int main(void) { unsigned short int h = 0x1234; unsigned short int n;
if (*((unsigned char *)&h) == 0x12) { printf("big-endian\n"); } if (*((unsigned char *)&h) == 0x34) { printf("little-endian\n"); }
n = htons(h);
if (*((unsigned char *)&n) == 0x12) {
printf("big-endian\n");
} else {
printf("little-endian\n");
}
return 0; }
或者:
#include <stdio.h> #include <arpa/inet.h> int main(){ unsigned long a = 0x12345678; unsigned char *p = (unsigned char *)(&a); printf("主机字节序:%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]); unsigned long b = htonl(a); //将主机字节序转化成了网络字节序 p = (unsigned char *)(&b); printf("网络字节序:%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]);
return 0; }
结果:
主机字节序:78 56 34 12
网络字节序:12 34 56 78
转化:
include <stdio.h> #include <arpa/inet.h> int main() { struct in_addr ipaddr; unsigned long addr = inet_addr("192.168.1.100"); printf("addr = %u\n", ntohl(addr)); ipaddr.s_addr = addr; printf("%s\n", inet_ntoa(ipaddr)); return 0; }
结果:
addr = 3232235876
129.168.1.100
参考:http://blog.csdn.net/msdnwolaile/article/details/50727653