Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP Address for a specific network interface on Ruby

Tags:

linux

ruby

I need to get the IP address for each of my network interfaces. The issue is that the standard ruby method Socket.ip_address_list only returns to me the adress list, but no information about which interface corresponds to the IP address.

#<Addrinfo: 127.0.0.1>
#<Addrinfo: 192.168.13.175>
#<Addrinfo: 172.17.0.1>
#<Addrinfo: ::1>
#<Addrinfo: fe80::4685:ff:fe0d:c406%wlan0>

I am basically looking for the equivalent of NodeJS os.networkInterfaces()[interfaceName].

How can I know the IP address for a specific network interface?

like image 967
Alberto Rivera Avatar asked Oct 28 '25 13:10

Alberto Rivera


1 Answers

Please let me know if there's a way to get this information using Ruby 1.9.X

I updated Ruby to 2.3 version and then used Socket.getifaddrs (available since Ruby 2.1).

require 'socket'
addr_infos = Socket.getifaddrs
addr_infos.each do |addr_info|
    if addr_info.addr
        puts "#{addr_info.name} has address #{addr_info.addr.ip_address}" if addr_info.addr.ipv4?
    end
end

Output:

$ ruby2.3 getInterfaces.rb 
lo has address 127.0.0.1
wlan0 has address 192.168.13.175
docker0 has address 172.17.0.1
like image 190
Alberto Rivera Avatar answered Oct 30 '25 07:10

Alberto Rivera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!