如何在 POSIX 2018 下查询我自己的 FQDN

如何在 POSIX 2018 下查询我自己的 FQDN

posix 的第 7 期已删除gethostbyname,因此我无法再gethostbyname("my_hostname")获取我的机器的规范主机名。我尝试使用getnameinfo代替,但给出了/etc/hosts类似

127.0.0.1 localhost
127.0.0.1 my_hostname.fqdn my_hostname

我要回来了localhost(这是有道理的)。但是确实gethostbyname("my_hostname")会返回my_hostname.fqdn(至少在 musl 和 glibc 下)。

是否有一个合理的替代方案可以替代第 7 期中的用例,或者我在这个用例上运气不好?

答案1

来自 Solaris 手册页:

DESCRIPTION
 These functions are used to obtain entries describing hosts.
 An  entry  can come from any of the sources for hosts speci-
 fied in the /etc/nsswitch.conf file.  See  nsswitch.conf(4).
 These      functions     have     been     superseded     by
 getipnodebyname(3SOCKET),   getipnodebyaddr(3SOCKET),    and
 getaddrinfo(3SOCKET),  which  provide greater portability to
 applications when multithreading is performed  or  technolo-
 gies  such  as  IPv6  are  used.  For example, the functions
 described in the following cannot be used with  applications
 targeted to work with IPv6.

如您所见,该函数getaddrinfo()也在 POSIX 标准中并受支持......

答案2

当前(尝试)确定当前主机的“规范”FQDN 的符合 POSIX 的方法是调用gethostname()确定配置的主机名,然后getaddrinfo()来确定对应的地址信息。

忽略错误:

char buf[256];
struct addrinfo *res, *cur;
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_CANONNAME;
hints.ai_socktype = SOCK_DGRAM;

gethostname(buf, sizeof(buf));
getaddrinfo(buf, 0, &hints, &res);
for (cur = res; cur; cur = cur->ai_next) {
    printf("Host name: %s\n", cur->ai_canonname);
}

结果高度依赖于系统和解析器配置。

相关内容