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.
Asked
Active
Viewed 1.9k times
3 Answers
20
This seems to work:
hostname = Socket.gethostbyname(Socket.gethostname).first

dvorak
- 31,281
- 4
- 27
- 29
-
On Mac OS X this seems to return the hostname in lowercase : `$ruby -e 'puts Socket.gethostbyname(Socket.gethostname).first' xin.local` in contrast to the bash 'hostname' command `$ hostname XIN.local` – asmaier May 19 '14 at 12:29
-
this solution is since ruby 2.7+ deprecated – VP. Jun 10 '21 at 06:56
-
2and what's the new solution? – Sixtyfive Oct 15 '21 at 20:05
6
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).

Alexis Lê-Quôc
- 1,023
- 7
- 8
-
2If the domain name isn't set on the machine, hostname -f will query DNS as well. – James Cape Sep 18 '12 at 15:13
-5
Could be a tad simpler => hostname = Socket.gethostname