views:

137

answers:

4

Just like the title says, wanted for testing purposes.

Thanks!

+2  A: 
ip = "%d.%d.%d.%d" % [rand(256), rand(256), rand(256), rand(256)]
yjerem
That won't always generate a valid address. (On rare occasions, it could generate `0.0.0.0` or `255.255.255.255` which are not valid addresses)
webdestroya
Do those two addresses break some rule? They look OK to me. Since the OP only asked a vague question, those two are just as good as any other.
dbasnett
If I remember right, they are good IP numbers but are pre-assigned to network broadcasts. No machine can have an IP of 0.0.0.0 or 255.255.255.255, but they can respond to requests to those numbers. If that makes sense in an application then it's OK to use them. See http://en.wikipedia.org/wiki/Broadcast_address for more info.
Greg
+5  A: 

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

Chubas
+2  A: 

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
jspooner
+5  A: 

You could use IPAddr

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