标签:
struct sockaddr_in { uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; char sin_zero[8]; };
struct sockaddr { uint8_t sin_len; sa_family_t sin_family; char sa_data[14]; };
最高有效位(MSB:Most Significant Bit)存储于最低内存地址处,最低有效位(LSB:Lowest Significant Bit)存储于最高内存地址处。
最高有效位(MSB:Most Significant Bit)存储于最高内存地址 处,最低有效位(LSB:Lowest Significant Bit)存储于最低内存地址处。
不同的主机有不同的字节序,如x86为小端字节序,Motorola 6800为大端字节序,ARM字节序是可配置的。
网络字节序规定为大端字节序
下面我们就写一个小程序来验证自己的机器是大端还是小端:
#include <stdio.h> #include <arpa/inet.h> int main(void) { unsigned int x = 0x12345678; unsigned char *p = (unsigned char*)&x; printf("%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]); return 0; }
字节序转换函数:
#include <stdio.h> #include <arpa/inet.h> int main(void) { unsigned int x = 0x12345678; unsigned char *p = (unsigned char*)&x; printf("%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]); unsigned int y = htonl(x); p = (unsigned char*)&y; printf("%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]); return 0; }
#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);
#include <stdio.h> #include <arpa/inet.h> int main(void) { unsigned long addr = inet_addr("192.168.0.100"); printf("addr=%u\n", ntohl(addr)); struct in_addr ipaddr; ipaddr.s_addr = addr; printf("%s\n", inet_ntoa(ipaddr)); return 0; }
标签:
原文地址:http://www.cnblogs.com/DamonBlog/p/4418978.html