如何在 Ruby 中获取当前主机的 FQDN?

发布于 2024-07-06 13:21:43 字数 143 浏览 5 评论 0原文

我需要获取运行 Ruby 脚本的主机的完全扩展主机名。 在 Perl 中,我使用 Sys::Hostname::Long 取得了良好的效果。 Google 似乎建议我应该在 ruby​​ 中使用 Socket.hostname,但这只是返回节点名,而不是完整的主机名。

I need to get the fully expanded hostname of the host that my Ruby script is running on. In Perl I've used Sys::Hostname::Long with good results. Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

開玄 2024-07-13 13:21:43

这似乎有效:

hostname = Socket.gethostbyname(Socket.gethostname).first 

This seems to work:

hostname = Socket.gethostbyname(Socket.gethostname).first 
凡间太子 2024-07-13 13:21:43
hostname = Socket.gethostbyname(Socket.gethostname).first

不推荐,并且只有在正确设置反向 DNS 解析时才有效。 如果需要,此 Facter bug 有更长的解释。

如果您阅读facter代码,您会注意到他们在某种程度上通过说完全回避了这个问题

fqdn = hostname + domainname

其中:

hostname = %[hostname]
domainname = %[hostname -f] # minus the first element

这是一个合理的假设,不依赖于 DNS 的设置(可能位于机器外部)。

hostname = Socket.gethostbyname(Socket.gethostname).first

is not recommended and will only work if your reverse DNS resolution is properly set up. This Facter bug has a longer explanation if needed.

If you read the facter code, you'll notice that they somewhat sidestep the issue altogether by saying:

fqdn = hostname + domainname

where:

hostname = %[hostname]
domainname = %[hostname -f] # minus the first element

This is a reasonable assumption that does not depend on the setup of DNS (which may be external to the box).

游魂 2024-07-13 13:21:43

可以简单一点=> 主机名 = Socket.gethostname

Could be a tad simpler => hostname = Socket.gethostname

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文