如何在 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);
}

結果高度依賴系統和解析器配置。

相關內容