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

Updated . Posted . Visible to the public.

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
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2013-01-15 08:28)