Search code examples
ruby-on-railsrubyip-address

How to generate a list of IP addresses between two addresses with Ruby


I have a user input a string of IP addresses they'd like to use. That string looks something like:

192.168.1.3-192.168.1.100

I'm trying to generate an array of IP addresses including, and between the start and end address, which would look something like:

["192.168.1.3","192.168.1.4",.....,"192.168.1.99","192.168.1.100"]

I was hoping it would be as simple as

("192.168.1.3".."192.168.1.100").step(1).to_a

but I guess it isn't.


Solution

  • Use IPAddr from the Ruby Stdlib.

    IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.

    require 'ipaddr'
    
    # I used a smaller number to limit the output
    ip_range = IPAddr.new("192.168.1.3")..IPAddr.new("192.168.1.13")
    ip_range.to_a
    

    The output is an array of IPAddr instances.

    => [#<IPAddr: IPv4:192.168.1.3/255.255.255.255>, #<IPAddr: IPv4:192.168.1.4/255.255.255.255>, #<IPAddr: IPv4:192.168.1.5/255.255.255.255>, #<IPAddr: IPv4:192.168.1.6/255.255.255.255>, #<IPAddr: IPv4:192.168.1.7/255.255.255.255>, #<IPAddr: IPv4:192.168.1.8/255.255.255.255>, #<IPAddr: IPv4:192.168.1.9/255.255.255.255>, #<IPAddr: IPv4:192.168.1.10/255.255.255.255>, #<IPAddr: IPv4:192.168.1.11/255.255.255.255>, #<IPAddr: IPv4:192.168.1.12/255.255.255.255>, #<IPAddr: IPv4:192.168.1.13/255.255.255.255>]
    

    A word of warning though. If you are taking user input make sure to catch the potential IPAddr::InvalidAddressError that can occur.

    begin 
      IPAddr.new(params[:from])..IPAddr.new(params[:to])
    rescue IPAddr::InvalidAddressError
      # @todo handle error
      logger.info("Oh Noes!")
    end