21

I want to generate some random IP Address. But evertime this generateIPAddress function returns 0.0.0.0 string as ipAddress. But it should be returning some random ipAddress other than 0.0.0.0 everytime. Any suggestions why is it happening?

private void callingGeoService() {
    int p1 = 255;
    int p2 = 0;
    int p3 = 0;
    int inc = 5;

    String ipAddress = generateIPAddress(p1, p2, p3);

    p3 += inc;
    if (p3 > 255) {
        p3 = 0;
        p2 += inc;
        if (p2 > 255) {
            p2 = 0;
            p1--;
            if (p1 <= 0) {
                p1 = 0;
            }
        }
    }
}

This is the generateIPAddress method

private String generateIPAddress(int p1, int p2, int p3) {

    StringBuilder sb = null;

    int b1 = (p1 >> 24) & 0xff;
    int b2 = (p2 >> 16) & 0xff;
    int b3 = (p3 >>  8) & 0xff;
    int b4 = 0;

    String ip1 = Integer.toString(b1);
    String ip2 = Integer.toString(b2);
    String ip3 = Integer.toString(b3);
    String ip4 = Integer.toString(b4);

    //Now the IP is b1.b2.b3.b4
    sb = new StringBuilder();
    sb.append(ip1).append(".").append(ip2).append(".").append(ip3).append(".").append(ip4);
    // System.out.println(sb);

    return sb.toString();

}

I want a random value assigned to ipAddress in the form of p1,p2,p3 and last bit should be 0.

Barry
  • 3,109
  • 7
  • 20
  • 40
AKIWEB
  • 16,538
  • 58
  • 164
  • 276
  • Java does not have such a thing as out-parameters – The Nail Feb 10 '12 at 23:22
  • What does that mean. I was not able to understand? – AKIWEB Feb 10 '12 at 23:23
  • Oh never mind; I thought you wanted to assign something to p1/p2/p3, but I was a bit too quick responding. Still not sure what the modification (`p3 += inc;` etc.) should do after calling `generateIPAddress`. I should have said: Java does not have method level static variables, since the modification of p1/p2/p3 will be lost after leaving the method scope. – The Nail Feb 10 '12 at 23:27
  • http://www.texamples.com/how-to-generate-random-passwords-in-java/ this might help you. – brainless Aug 28 '12 at 18:35

9 Answers9

54
Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
Guillaume Polet
  • 45,783
  • 4
  • 79
  • 115
  • 3
    This generates a whole bunch of questionable addresses; things like 0.0.0.0 and 255.255.255.255, as well as private IP address ranges and multicast addresses. – joev Feb 10 '12 at 23:50
  • 1
    255.255.255.255 is the universal broadcast address. use this one with cautions ! – 0xBAADF00D Jul 17 '13 at 06:41
12

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.

gilad
  • 418
  • 5
  • 10
3

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]
Barry
  • 3,109
  • 7
  • 20
  • 40
Andrei Ciobanu
  • 11,585
  • 20
  • 75
  • 115
1

To generate random IP address with Subnet Mask use the below code (Note that in this code Subnet Mask has CIDR format):

import java.util.Random;
import java.util.Scanner;

public class mainClas {

    public static int findRange(int mask)
    {
        int x = 8 - mask;
        int sum = 0;
        for (int i = 0 ; i < x ; i++) {
            sum += Math.pow(2 , i);
        }
        return sum;
    }

    public static int findFixedPart(String IPPrefix, int i)
    {
        String f = IPPrefix.split("\\.")[i];
        return Integer.valueOf(f);
    }

    public static String generateRandomIP(String IPPrefix, Integer mask)
    {
        String IP="";
        Random r = new Random();
        if (mask < 8)
            IP = (findFixedPart(IPPrefix, 0) + r.nextInt(findRange(mask))) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >7 && mask < 16)
            IP = findFixedPart(IPPrefix, 0) + "." + (findFixedPart(IPPrefix, 1) + r.nextInt(findRange(mask-8))) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >15 && mask < 24)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + (findFixedPart(IPPrefix, 2) + r.nextInt(findRange(mask-16))) + "." + r.nextInt(256);
        else if (mask >23 && mask < 33)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + findFixedPart(IPPrefix, 2) + "." + (findFixedPart(IPPrefix, 3) + r.nextInt(findRange(mask-24)));
        return IP;
    }

    public static void main(String[] inpout)
    {

        System.out.println("Enter IP Prefix: ");
        Scanner sc = new Scanner(System.in);
        String IPPrefix = sc.nextLine();
        System.out.println("Enter Mask: ");
        Integer mask = sc.nextInt();

        // Find random IP in Subnet mask
        String IP = generateRandomIP(IPPrefix, mask);
        System.out.println(IP);
    }
}
0

Assuming that you don't actually care about the resultant IP address being valid in any form whatsoever, you have a simple problem.

The code for generating the addresses sets the parameters p3 and p2 to something less than 255. p1 is trapped between 255 and 0.

The real problem is that the code that turns this into an address shifts these values. p1 by 24, p2 by 16 and p3 by 8. Understanding the limitation applied in the calling method, you can know that p1, p2 and p3 will never exceed 255, so in this case knowing that a shift of 8 or more will result in 0, none of the individual elements of the address will result in a value other than 0, and the last octet will always be 0, so the resultant address will be 0.0.0.0

If you want to prevent it from being 0.0.0.0, the first thing to do is remove the shift operations. This will still keep the last field as 0, because it is never set, but it should produce addresses.

Again, this is not caring about the state of the addresses, you will end up with broadcast, multicast and local-only addresses using this method.

Petesh
  • 82,900
  • 3
  • 91
  • 111
0

When you invoke generateIPAddress(p1, p2, p3), p1 is 255, p2 and p3 are 0.

This line

int b1 = (p1 >> 24) & 0xff;

shifts p1 24 bits to the right. Before the shift p1 was 11111111. The shift results with 0. Actually you could also use

int b1 = p1 >> 8;

as p1 has only its 8 least significant bits turned on. The use of & 0xff is redundant as the operation is between two int operands. So b1 is 0.

p2 and p3 are passed with the value 0 so the shift (either by 16 or 8) doesn't change it one bit, resulting with b2 and b3 being also 0.

b4 is explicitly set to 0.

So all b1, b2, b3 and b4 are 0, from which you create ip1 to ip4. So the method generateIPAddress(p1, p2, p3) always returns 0.0.0.0.

Then p3 += inc; adds 5 to 0. Reuslt in p3 now is 5.

The condition if (p3 > 255) will always fail as p3 is 5 which is < 255...

yair
  • 8,197
  • 3
  • 28
  • 49
0

this function will help you to generate an infinite number of a random IP address:

        StringBuilder ip = new StringBuilder("xx.xx.xx.xx");
            for (int i=0 ; i <11;i++){

                if (i==2){}
                else if (i==5){}
                else if (i==8){}
                else{
                    Random r = new Random();
                    int random = r.nextInt((9 - 1) + 1) + 1;
                    char c = (char)(random+'0');
                    ip.setCharAt(i, c);
                }

            }

            Log.v("ip","Server IP : "+ip);

As you see i generate xx.xx.xx.xx ip format and you can handle it to generate any ip format.

  • An IPv4 address is not "xx.xx.xx.xx", it is 4 8-bit integers, or one 32-bits integer if you prefer. By just avoiding the first digit in a 10-based output, you just restrict the outgoing space of possible values, for no reasons. – Patrick Mevzek Dec 10 '19 at 22:14
0

I wrote a short code to filter out ranges listed in wikipedia as special (slightly more as only based on 1st octet):

Random r = new Random();
Integer prefix;
while ({
    prefix = r.nextInt(256);
    prefix in [0,10,100,127,172,192,198,203,224,240,255]
}());   
return prefix + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
Alexei Martianov
  • 2,291
  • 3
  • 23
  • 50
0

A very simple and fast way to generate a random ip address:

import java.util.Random;

public class IpAddressHelper {

     public static String createRandom() {
         return randomNumber() + "." + randomNumber() + "." + randomNumber() + "." + randomNumber();
     }

     public static int randomNumber() {
         return new Random().nextInt((255 - 1) + 1) + 1;
     }
}