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
From coderrr.wordpress.com:
require 'socket'def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last endensure Socket.do_not_reverse_lookup = origend# irb:0> local_ip# => "192.168.0.127"
Try this:
host = `hostname`.strip # Get the hostname from the shell and removing trailing \nputs host # Output the hostname