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

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_addressend

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


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


require 'socket'Socket::getaddrinfo(Socket.gethostname,"echo",Socket::AF_INET)[0][3]

quite like method 1, actually