Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to convert IP range to array of IP's

Tags:

ruby

ip

Is there any easy way to convert IP range to array of IPs?

def convertIPrange (start_ip, end_ip)
 #output: array of ips end
end

e.g. input

('192.168.1.105', '192.168.1.108') 

output

['192.168.1.105','192.158.1.106','192.158.1.107','192.158.1.108']
like image 626
TheOneTeam Avatar asked Dec 15 '22 03:12

TheOneTeam


2 Answers

Use the Ruby standard library IPAddr

# I would suggest naming your function using underscore rather than camelcase
# because of Ruby naming conventions
#
require 'ipaddr'

def convert_ip_range(start_ip, end_ip)
  start_ip = IPAddr.new(start_ip)
  end_ip   = IPAddr.new(end_ip)

  # map to_s if you like, you can also call to_a, 
  # IPAddrs have some neat functions regarding IPs, 
  # be sure to check them out
  #
  (start_ip..end_ip).map(&:to_s) 
end
like image 83
Beat Richartz Avatar answered Dec 29 '22 11:12

Beat Richartz


def convertIPrange first, last
  first, last = [first, last]
    .map{|s| s.split(".").inject(0){|i, s| i = 256 * i + s.to_i}}
  (first..last).map do |q|
    a = []
    (q, r = q.divmod(256)) && a.unshift(r) until q.zero?
    a.join(".")
  end
end

convertIPrange('192.168.1.105', '192.168.1.108')
# => ["192.168.1.105", "192.168.1.106", "192.168.1.107", "192.168.1.108"]

convertIPrange('192.255.255.254', '193.0.0.1')
# => ["192.255.255.254", "192.255.255.255", "193.0.0.0", "193.0.0.1"]
like image 29
sawa Avatar answered Dec 29 '22 11:12

sawa