Read more

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

Arne Hartherz
January 15, 2013Software engineer at makandra GmbH

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

>> Socket.gethostname
=> "happycat"
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2013-01-15 09:28)