我遇到了以下代码快照:
struct hostent *hp;
hp = my_gethostbyname(localhost);
if (hp == NULL) {
ls_syslog(LOG_ERR, I18N_FUNC_FAIL, fname, "my_gethostbyname()");
return -1;
}
strcpy(localhost, hp->h_name);
memcpy(&addr, hp->h_addr, hp->h_length);
最后一句话让我很困惑,structhostent的声明是这样的:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
它没有一个名为"h_addr"的字段,但代码确实可以编译,有人能告诉我为什么吗?谢谢
您错过了下面的这一点:
#define h_addr h_addr_list[0] /* for backward compatibility */
所以不,没有问题。
在GNU libc手册中(或者在一页上查看整个libc手册),他们说:
回想一下,主机可能连接到多个网络,并且每个上都有不同的地址
它们还提供了h_addr
变量,该变量只是矢量h_addr_list
的第一个元素。
h_addr
不是POSIX。参见POSIX netdb.h。使用h_addr
可能导致error: ‘struct hostent’ has no member named ‘h_addr’
。可移植代码应该使用h_addr_list
。
_BSD_SOURCE
和/或_DEFAULT_SOURCE
,h_addr
宏在某些系统上才可见。