【问题标题】:How can I get the system's IP address(es) AND (their) associated MAC address in Ruby?如何在 Ruby 中获取系统的 IP 地址和(它们的)相关 MAC 地址?
【发布时间】:2016-05-10 20:06:49
【问题描述】:

根据Ruby - Platform independent way to determine IPs of all network interfaces?,我们知道“从 Ruby 2.1 开始,Socket#getifaddrs 可用”,甚至还有一个如何使用它获取机器 IP 的代码示例。

macaddr gem,有一些代码可以找到MAC地址,同样使用Socket#getifaddrs。

但是,将两者结合起来是我的头上。

想要的输出是:

{name: {physical_address: macaddress, ip_addresses: [ip1, ip2, ip3..]}}

地点:

  • name 是每个设备的名称(例如“en0”、“en1”等)
  • macaddress为MAC地址(如00:28:00:43:37:eb
  • ip_addresses 是一个数组,其中包含与该 MAC 地址关联的所有 IP 地址

我们如何使用我们拥有的工具将所有部分连接在一起?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您可以从 Socket.getifaddrs 元素中提取接口名称:

    require 'socket'
    Socket.getifaddrs.each { |if_addr| puts if_addr.name }
    

    通过类似的方式,您还可以获得与名称相关的 IP 地址:

    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
    

    最后,MAC 地址大致相同:

    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
    

    注意:某些接口不能有 MAC 地址并返回空数组

    你只需要加入它就有你的哈希:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      相关资源
      最近更新 更多