I have searched everywhere but their solution requires some form of IP address. Here are the solutions i have found.
require \'socket\'
#METHOD 1
ip
parse the output of the ip
command?
from https://gist.github.com/henriquemenezes/a99f13da957515023e78aea30d6c0a48
gw = `ip route show`[/default.*/][/\d+\.\d+\.\d+\.\d+/]
or parse the output of the ipconfig
command: https://stackoverflow.com/a/12632929/32453
require 'socket'
Socket::getaddrinfo(Socket.gethostname,"echo",Socket::AF_INET)[0][3]
quite like method 1, actually
This is what I've been using in production for years:
require 'socket'
ip = Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
ip.ip_address
Works great; tested on aws and classical hosting
As there is no such thing as a default ip-interface to a host (there does not need to be any ip-interface at all actually) all assumptions regarding nameing are vague, do not necessarily hold.
The value returned by gethostname()
can be defined independently to any ip-setup, so it does not need to reflect a valid host in terms of a hostname which could be resolved to any ip-address.
From the POSIX system's API's view the only reliabe function to test for the availablily of (ip-)interfaces is the function getifaddrs()
, which returns a list of all interfaces along with their parameters.
As it looks as if Ruby's current Socket lib does not provide an interface to it, this (http://rubygems.org/gems/system-getifaddrs) gem based approach does seem to be the only way to go.
Isn't the solution you are looking for just:
require 'socket'
addr_infos = Socket.ip_address_list
Since a machine can have multiple interfaces and multiple IP Addresses, this method returns an array of Addrinfo.
You can fetch the exact IP addresses like this:
addr_infos.each do |addr_info|
puts addr_info.ip_address
end
You can further filter the list by rejecting loopback and private addresses, as they are usually not what you're interested in, like so:
addr_infos.reject( &:ipv4_loopback? )
.reject( &:ipv6_loopback? )
.reject( &:ipv4_private? )