Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the FQDN of the current host in Ruby?

Tags:

ruby

fqdn

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.

like image 490
dvorak Avatar asked Sep 30 '08 02:09

dvorak


2 Answers

This seems to work:

hostname = Socket.gethostbyname(Socket.gethostname).first 
like image 158
dvorak Avatar answered Sep 22 '22 06:09

dvorak


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).

like image 31
Alexis Lê-Quôc Avatar answered Sep 26 '22 06:09

Alexis Lê-Quôc