Reputation: 621
As per Ruby - Platform independent way to determine IPs of all network interfaces? we know that "As of Ruby 2.1, Socket#getifaddrs is available", and there is even a code example of how to get the machine's IP using it.
From the macaddr gem, there is some code to find the MAC address, also using Socket#getifaddrs.
However, it's above my head to combine the two.
The desired output is:
{name: {physical_address: macaddress, ip_addresses: [ip1, ip2, ip3..]}}
Where:
name
is each device name (such as 'en0', 'en1', and so-on)macaddress
is the MAC address (such as 00:28:00:43:37:eb
)ip_addresses
is an array that contains all the IP addresses associated with that MAC addressHow can we use the tools we have to connect all the pieces together?
Upvotes: 1
Views: 981
Reputation: 316
You can extract interface names from Socket.getifaddrs elements:
require 'socket'
Socket.getifaddrs.each { |if_addr| puts if_addr.name }
In a similar way you can also get de IP addresses related to the names:
require 'socket'
Socket.getifaddrs.each do |if_addr|
next unless if_addr.addr.ipv4?
puts "#{if_addr.name} => #{if_addr.addr.ip_address.to_s}"
end
And finally more or less the same for the MAC address:
require 'socket'
Socket.getifaddrs.each do |if_addr|
next unless if_addr.addr.pfamily == Socket::PF_LINK
puts "#{if_addr.name} => #{if_addr.addr.getnameinfo}"
end
Note: Some interfaces could not have a MAC address an returns empty arrays
You only have to join it have your hash :)
Upvotes: 2