I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?
Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):
The [below] code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.
Hostname
A simple way to just get the hostname in Ruby is:
The catch is that this relies on the host knowing its own name because it uses either the
gethostname
oruname
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:The accepted answer works but you have to create a socket for every request and it does not work if the server is on a local network and/or not connected to the internet. The below, I believe will always work since it is parsing the request header.
try: Request.remote_ip
Update: Oops, sorry I misread the documentation.
From coderrr.wordpress.com:
The couple of answers with
require 'socket'
look good. The ones with request.blah_blah_blah assume that you are using Rails.IO should be available all the time. The only problem with this script would be that if
ifconfig
is output in a different manor on your systems, then you would get different results for the IP. The hostname look up should be solid as Sears.This IP address used here is Google's, but you can use any accessible IP.