Alberto Rivera
Alberto Rivera

Reputation: 3752

Get IP Address for a specific network interface on 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?

Upvotes: 4

Views: 2751

Answers (2)

user246672
user246672

Reputation:

One-liner

require 'socket'; Socket.getifaddrs.map(&:addr).select(&:ipv4?).map(&:ip_address).select { |x| x !~ /\A127/ }

Upvotes: 0

Alberto Rivera
Alberto Rivera

Reputation: 3752

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

Upvotes: 6

Related Questions