Search code examples
rubyipsubnet

How to get a random IP from an IP range/subnet?


Let's suppose, I have the IP Range: "52.93.50.128/32" How can I get a random IP address that in that range?

Ruby would be preferable.


Solution

  • I think that this snippet using this gem should work, the easy way is to calculate the IPs range, and then select a new

    #!/usr/bin/env ruby
    
    require 'ipaddr'
    
    family = Socket::AF_INET
    
    subnet_range = IPAddr.new("52.93.50.128/32", family).to_range
    from = subnet_range.first(2).last
    to = IPAddr.new(subnet_range.last.to_i - 2, family)
    
    puts "From: #{from}"
    puts "To: #{to}"
    
    random_ip = IPAddr.new(rand(from.to_i..to.to_i), family)
    
    puts "Random IP: #{random_ip}"