50

I am trying to get the hostname of the machine which a rails application is running on from the controller.

What would be the best way to do this taking into account it should work on both windows and linux?

sth
  • 222,467
  • 53
  • 283
  • 367
RailsSon
  • 19,897
  • 31
  • 82
  • 105

4 Answers4

99

All you have to do is look at the request object in your controller:

request.host_with_port

or if you don't want the port, just

request.host
Wilhelm
  • 6,506
  • 5
  • 30
  • 26
  • 1
    this is helpful for if you are trying to parse URL's and such, but I think this particular question pertains to the actual name of that machine or OS. – taelor Sep 22 '11 at 18:11
  • this wont help you if you want to get the internal name of the host – phoet Nov 01 '11 at 09:30
31

There's always:

require 'socket'
...
Socket.gethostname

I've got no Windows box handy with which to test this, but the docs make no mention of it being *nix specific.

Note: The require statement is not necessary for Rails 4, and probably other Rails versions as well. It is required if you are doing plain Ruby without Rails.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
9

Use backticks and the command hostname

current_host = `hostname`

This sends the command to the shell, and returns the hostname. Works on at least: Debian Linux, Windows, Solaris.

btelles
  • 5,390
  • 7
  • 46
  • 78
2

If you need the full domain path from protocol to port, try:

full_domain_path = request.env['rack.url_scheme'] + '://' + request.host_with_port
webaholik
  • 1,619
  • 1
  • 19
  • 30