Sha256: b547da3b827b7770f7ae1303414d258c500b24bde893b3a1ce30dd06e7750d37

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

require "macaddr"

module MQTT
  module Homie
    module Network
      def default_localip
        addr = default_interface[:addresses][0] if default_interface
        addr ? addr.ip_address : nil
      end

      def default_mac
        (default_interface ? default_interface[:hwaddr] : nil) || Mac.addr
      end

      def default_interface
        @default_interface ||= interfaces.values.find { |i| i[:default] }
      end

      def interfaces
        @interfaces ||= begin
          interfaces = {}
          found = false
          Socket.getifaddrs.each do |ifaddr|
            ifname = ifaddr.name
            data = interfaces[ifname] ||= { addresses: [] }
            next unless addr = ifaddr.addr
            data[:addresses].push addr if (addr.ipv4? || addr.ipv6?) && usable_address?(addr)
            data[:hwaddr] = $1 if addr.inspect.match(/hwaddr=([0-9a-fA-F:]+)/)  # doesn't work on windows
            data[:default] = true unless found
            data[:name] = ifname
            found = true
          end
          interfaces
        end
      end

      def usable_address?(addr)
        !(addr.ipv4_loopback? || addr.ipv6_loopback? || addr.ipv4_multicast? || addr.ipv6_linklocal?)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mqtt-homie-0.1.1 lib/mqtt/homie/network.rb