Generate Random IP Address

2019-04-19 09:03发布

问题:

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.

回答1:

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


回答2:

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.



回答3:

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);
    }
}


回答4:

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]


回答5:

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.



回答6:

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...



标签: java ip subnet