Java – generate random IP address

I want to generate some random IP addresses But the generateipaddress function returns 0.0 0.0 string as IPAddress But it should return 0.0 every time Random IPAddress other than 0.0 Why did any suggestion happen?

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 some random IPaddresses. Basically, I have hard coded initial IPAddress bits in the form of P1 and P3, and the last bit should be 0

Solution

Random r = new Random();
Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>