Linux struct hostent 是否有字段“h_addr”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11405819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:46:08  来源:igfitidea点击:

Does struct hostent have a field "h_addr"?

linuxhostent

提问by wangshuaijie

I encountered the following code snapshot:

我遇到了以下代码快照:

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);

I am rather confused by the last statement, the declaration of struct hostent is like this:

我对最后一条语句感到很困惑,struct hostent 的声明是这样的:

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 */
};

It doesn't have a field named "h_addr", but the code did can compile, can anyone tell me why? thanks.

它没有名为“h_addr”的字段,但代码确实可以编译,谁能告诉我为什么?谢谢。

采纳答案by Ignacio Vazquez-Abrams

You missed this bit right under it:

你错过了它下面的这一点:

#define h_addr h_addr_list[0] /* for backward compatibility */

So no, there is no problem.

所以不,没有问题。

回答by Ratul Sharker

In the GNU's documentation pagethey says

GNU 的文档页面中,他们说

"Recall that the host might be connected to multiple networks and have different addresses on each one"

“回想一下,主机可能连接到多个网络,并且每个网络都有不同的地址”

they also provide a h_addrwhich is just the first element of the vector h_addr_list.

他们还提供了 ah_addr这只是 vector 的第一个元素h_addr_list

回答by kralyk

Note that the h_addrmacro is on some systems only visible if you define _BSD_SOURCEand/or _DEFAULT_SOURCEbefore including header files.

请注意,h_addr只有在定义_BSD_SOURCE和/或_DEFAULT_SOURCE包含头文件之前,宏在某些系统上才可见 。

回答by mortmann

h_addris not POSIX. See POSIX netdb.h. Using h_addrcould result in error: ‘struct hostent' has no member named ‘h_addr'. Portable code should use h_addr_listinstead.

h_addr不是POSIX。请参阅POSIX netdb.h。使用h_addr可能会导致error: ‘struct hostent' has no member named ‘h_addr'. 应改用可移植代码h_addr_list