Sha256: 570a6c1f1a6c2d1a7fec7b06ebdd541b25eea054a6f6a02d38865e1875434583

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 KB

Contents

require 'ipaddr'

module LinuxAdmin
  class IpAddress
    include Common

    def address
      address_list.detect { |ip| IPAddr.new(ip).ipv4? }
    end

    def address6
      address_list.detect { |ip| IPAddr.new(ip).ipv6? }
    end

    def mac_address(interface)
      result = run(cmd("ip"), :params => ["addr", "show", interface])
      return nil if result.failure?

      parse_output(result.output, %r{link/ether}, 1)
    end

    def netmask(interface)
      result = run(cmd("ifconfig"), :params => [interface])
      return nil if result.failure?

      parse_output(result.output, /netmask/, 3)
    end

    def gateway
      result = run(cmd("ip"), :params => ["route"])
      return nil if result.failure?

      parse_output(result.output, /^default/, 2)
    end

    private

    def parse_output(output, regex, col)
      the_line = output.split("\n").detect { |l| l =~ regex }
      the_line.nil? ? nil : the_line.strip.split(' ')[col]
    end

    def address_list
      result = nil
      # Added retry to account for slow DHCP not assigning an IP quickly at boot; specifically:
      # https://github.com/ManageIQ/manageiq-appliance/commit/160d8ccbfbfd617bdb5445e56cdab66b9323b15b
      5.times do
        result = run(cmd("hostname"), :params => ["-I"])
        break if result.success?
      end

      result.success? ? result.output.split(' ') : []
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
linux_admin-0.14.0 lib/linux_admin/ip_address.rb
linux_admin-0.13.0 lib/linux_admin/ip_address.rb
linux_admin-0.12.1 lib/linux_admin/ip_address.rb
linux_admin-0.12.0 lib/linux_admin/ip_address.rb