14

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.

dvorak
  • 31,281
  • 4
  • 27
  • 29

3 Answers3

20

This seems to work:

hostname = Socket.gethostbyname(Socket.gethostname).first 
dvorak
  • 31,281
  • 4
  • 27
  • 29
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
-5

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