How to get the hostname of the current machine in Rails or a Ruby script

Use Socket.gethostname. So for a machine whose hostname is "happycat", it will look like this:

>> Socket.gethostname
=> "happycat"

That should work right away for your Rails application. For plain Ruby, you first need to do:

require 'socket'

If you don't want to use Socket for some reason, you can still just use the hostname command, at least on non-Windows machines. Keep in mind that you need to remove trailing white space from the result of the system call.

>> `hostname`
=> "happycat\n"
>> `hostname`.strip
=> "happycat"

Note that this is about the machine's hostname, which can (and most often is) different from the host that a user is requesting in their current Rails session (request.host).

Also keep in mind that hostname might give you the FQDN depending on the configuration, i.e. something like foo-host.domain.tld.

Arne Hartherz Over 11 years ago