How to get my machine’s IP address from Ruby without leveraging from other IP address?

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? )

Leave a Comment