Generate Random IP Address

Using Google Guava:

import com.google.common.net.InetAddresses;
...
String ipString = InetAddresses.fromInteger(random.nextInt()).getHostAddress();

of course you can validate the resulting address not to be multicast etc.


I've recently developed a small library that can generate random IPv4 addresses using different type constraints:

MockNeat mock = MockNeat.threadLocal();

String ipv4 = mock.ipv4s().val();
System.out.println(ipv4);

String ipClassA = mock.ipv4s().type(CLASS_A).val();
System.out.println(ipClassA);

String classAorB = mock.ipv4s().types(CLASS_A, CLASS_B).val();
System.out.println(classAorB);

List<String> ip4s = mock.ipv4s().list(10).val();
System.out.println(ip4s);

Output:

192.112.222.183
120.178.110.193
143.68.176.47
[112.246.76.178, 29.201.72.151, 67.105.2.128, 102.189.109.206, 157.146.176.212, 59.220.145.35, 47.171.185.233, 162.245.163.124, 19.203.21.194, 114.177.238.50]

Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);

Tags:

Java

Ip

Subnet