Getting the Hostname or IP in Ruby on Rails

Hostname

A simple way to just get the hostname in Ruby is:

require 'socket'
hostname = Socket.gethostname

The catch is that this relies on the host knowing its own name because it uses either the gethostname or uname system call, so it will not work for the original problem.

Functionally this is identical to the hostname answer, without invoking an external program. The hostname may or may not be fully qualified, depending on the machine’s configuration.


IP Address

Since ruby 1.9, you can also use the Socket library to get a list of local addresses. ip_address_list returns an array of AddrInfo objects. How you choose from it will depend on what you want to do and how many interfaces you have, but here’s an example which simply selects the first non-loopback IPV4 IP address as a string:

require 'socket'
ip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address

Leave a Comment