sockaddr_in:这个结构体用于处理ip地址,便于进行通信,来自netinet/in.h
相关的其他两个结构体:
sockaddr和in_addr
定义:
struct sockaddr_in { short sin_family; unsigned short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; struct sockaddr { unsigned short sa_family; char sa_data[14]; }; struct in_addr { unsigned long s_addr; };
关于网络地址的转换:
inet_addr(), inet_aton()和inet_ntoa()可以参考:http://haoyuanliu.github.io/2017/01/15/%E5%9C%B0%E5%9D%80%E8%BD%AC%E6%8D%A2%E5%87%BD%E6%95%B0inet-addr-inet-aton-inet-ntoa-%E5%92%8Cinet-ntop-inet-pton/
注意:
inet_addr()和inet_aton()都将点分十进制转换成网络字节序
函数的返回值
inet_addr()不能转换255.255.255.255!
关于 in_addr_t:
typedef uint32_t in_addr_t;//uint32_t定义在<stdint.h>中
INADDR_ANY表示ip地址0.0.0.0,也就是本机的所有地址,位于netinet/in.h
关于字节序的转换:
htonl --> Host To Network, type Long
ntohl --> Network To Host, type Long
htons,ntohs:s-->short
#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);