hostent h_addr_list
struct hostent {
char FAR * h_name; /* official name of host */
char FAR * FAR * h_aliases; /* alias list */
short h_addrtype; /* host address type */
short h_length; /* length of address */
char FAR * FAR * h_addr_list; /* list of addresses */
#define h_addr h_addr_list[0] /* address, for backward compat */
};
h_addr_list其实是一个指针数组,数组中每个元素都是in_addr型指针。
typedef struct in_addr {
union {
struct { UCHAR s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { USHORT s_w1,s_w2; } S_un_w;
ULONG S_addr;
} S_un;
#define s_addr S_un.S_addr /* can be used for most tcp & ip code */
#define s_host S_un.S_un_b.s_b2 // host on imp
#define s_net S_un.S_un_b.s_b1 // network
#define s_imp S_un.S_un_w.s_w2 // imp
#define s_impno S_un.S_un_b.s_b4 // imp #
#define s_lh S_un.S_un_b.s_b3 // logical host
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
因为hostent结构支持多种地址类型,所以其定义的h_addr_list是char **型。gethostbyname以后,实际存储情况是这样:
hostent->h_addr_list[0][0] = 127
hostent->h_addr_list[0][1] = 0
hostent->h_addr_list[0][2] = 0
hostent->h_addr_list[0][3] = 1
得到的地址是网络字节顺序。转成正常的字符:
char *ip;
ip = inet_ntoa(*(struct in_addr *)*phost->h_addr_list);
向sockaddr_in赋值:
struct sockaddr whereto;
struct sockaddr_in *to;
memset(&whereto, 0, sizeof(struct sockaddr));
to = (struct sockaddr_in *)&whereto;
memcpy(&to->sin_addr, hp->h_addr, hp->h_length);