Ben Crouse
Ben Crouse

Reputation: 8348

What's the shortest way to generate a random IP address in Ruby?

Just like the title says, wanted for testing purposes.

Upvotes: 17

Views: 8450

Answers (7)

lzap
lzap

Reputation: 17174

To generate valid IP addresses within a reasonable network range (e.g. 10.0.0.0/24 or 2001:db8::/64), do this:

require 'ipaddr'
ipv4 = IPAddr.new("10.0.0.0/24", Socket::AF_INET) | IPAddr.new(rand(2**(32-24)),Socket::AF_INET)
ipv6 = IPAddr.new("2001:db8:cafe:babe::/64", Socket::AF_INET6) | IPAddr.new(rand(2**(128-64)),Socket::AF_INET6)

This can be generalized to any subnet:

subnet = "192.168.100.0"
prefix = 24
ipv4 = IPAddr.new("#{subnet}/#{prefix}", Socket::AF_INET) | IPAddr.new(rand(2**(32-prefix)),Socket::AF_INET)

Upvotes: 0

Bob Smith
Bob Smith

Reputation: 151

I was going to tack on to Lass's comment with some code to get any safe RFC1918 address, but not enough reputation yet.

So, if we take the following math results:

10*2**24 = 167772160
172*2**24 + 16*2**16 = 2886729728
192*2**24 + 168*2**16 = 3232235520

and, stuff them into an array which is stuffed in the IPAddr.new method

IPAddr.new([167772160, 2886729728, 3232235520].sample + rand(2**16), Socket::AF_INET)

Most any RF1918 space is generated. Unfortunately, this will always produce 10.0.X.X addresses, but that should be fine for testing if one was looking for some address variety in a not too terrible looking one-liner format.

A major benefit of something like this or Lass's method over Faker is there is reduced risk for accidental taxing of someone's Internet resources if the code attempts to reach out to the random address for some reason.

Upvotes: 0

Edmond Chui
Edmond Chui

Reputation: 659

I would suggest using Faker

https://github.com/stympy/faker#fakerinternet

Faker::Internet.ip_v4_address #=> "24.29.18.175"

Upvotes: 14

Aaron Lee
Aaron Lee

Reputation: 5457

You could use IPAddr

require 'ipaddr'
ipv4 = IPAddr.new(rand(2**32),Socket::AF_INET)
ipv6 = IPAddr.new(rand(2**128),Socket::AF_INET6)

Upvotes: 31

jspooner
jspooner

Reputation: 11315

I've used this before to generate a random ip then validate it with Resolv

  ip = "#{rand(99)}.#{rand(100)}.#{rand(10)}.#{rand(255)}"
  begin
    if ip
      host = Resolv.new.getname(ip) 
      puts "#{c} #{real_ip.length} #{ip} #{host}" 
    end
  rescue Exception => e
    puts "FAKE #{ip}"
  end

Upvotes: 2

Chubas
Chubas

Reputation: 18043

If you want a truly random IP address, Array.new(4){rand(256)}.join('.') does it

Upvotes: 19

Paige Ruten
Paige Ruten

Reputation: 176665

ip = "%d.%d.%d.%d" % [rand(256), rand(256), rand(256), rand(256)]

Upvotes: 3

Related Questions