Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random IP Address

Tags:

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.

like image 792
AKIWEB Avatar asked Feb 10 '12 23:02

AKIWEB


People also ask

Can I create my own IP address?

Your public IP address is usually set by your internet service provider (ISP), and you can't choose it yourself. However, you can "coax" it to change in any of several different ways: Change your network or location: Your public IP address will change based on where and how you connect to the internet.


1 Answers

Random r = new Random(); return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256); 
like image 117
Guillaume Polet Avatar answered Oct 08 '22 16:10

Guillaume Polet