0

I am trying to get a random ip address from given range.

EX: startIp = "192.168.1.0" ; endIp = "192.168.2.255"

I tried of converting range to cidr and getting randomIp for cidr list using SubnetUtils but no luck.

Is there any effective way of generating a random ip from given ip-range or an api which can do this?

Thanks in advance.

Forece85
  • 428
  • 1
  • 6
  • 22

1 Answers1

2

You can achieve by following the steps:

  1. Convert the two IPs to numeric values
InetAddress i= InetAddress.getByName(IPString);
int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt();
  1. Generate random between the limits
r.nextInt(High-Low) + Low;
  1. Convert result back numeric to IP
i= InetAddress.getByName(String.valueOf(intRepresentation));
String ip= i.getHostAddress();
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • this approach working fine till max of 128.255.255.255. For remaining its returning negative values and resulting below excpetion: `Exception in thread "main" java.net.UnknownHostException: -847933385 at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source) at java.net.InetAddress.getAddressesFromNameService(Unknown Source) at java.net.InetAddress.getAllByName0(Unknown Source) at java.net.InetAddress.getAllByName(Unknown Source) .....` – Forece85 Sep 02 '18 at 16:56
  • @Forece85 convert to long instead see https://stackoverflow.com/questions/10087800/convert-a-java-net-inetaddress-to-a-long – Ori Marko Sep 02 '18 at 17:01