joshfindit
joshfindit

Reputation: 621

How can I get the system's IP address(es) AND (their) associated MAC address in Ruby?

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:

How can we use the tools we have to connect all the pieces together?

Upvotes: 1

Views: 981

Answers (1)

rgo
rgo

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

Related Questions