Hostname
An easy way to get the hostname in Ruby:
require 'socket' hostname = Socket.gethostname
The trap is that it depends on the host, knowing its own name, because it uses the gethostname or uname system call, so it will not work for the original problem.
Functionally, this is identical to the hostname response without calling an external program. The host name may or may not be fully qualified, depending on the configuration of the machine.
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 it, it will depend on what you want to do and how many interfaces you have, but here is an example that simply selects the first IP address of an IP address without a loop as a string:
require 'socket' ip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
Tim Peters Oct 08 '09 at 4:00 2009-10-08 04:00
source share