Today I'll Show You How To Generate Random IP Address...
But First Why I Want This...Right...?
Ans : If You Want Test Your Code That Whether It Is Recognizing The Machine By It’s IP Address Then You Had To Use This Code To Generate Random IP Address.
So Here We Goooo....
private String generateIPAddress(int p1, int p2, int p3) { StringBuilder sb = null;
Random r1 = new Random(); Random r2 = new Random(); Random r3 = new Random(); Random r4 = new Random(); String ip1 = Integer.toString(b1); String ip2 = Integer.toString(b2); String ip3 = Integer.toString(b3); String ip4 = Integer.toString(b4); String b1 = IpConverter.longToIp(r1.nextLong()); String b2 = IpConverter.longToIp(r2.nextLong()); String b3 = IpConverter.longToIp(r3.nextLong()); String b4 = IpConverter.longToIp(r4.nextLong()); //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(); }
The Random Method is used to generate random number in java,In this case we have to generate four
hence
hence
Random r1 = new Random(); Random r2 = new Random(); Random r3 = new Random(); Random r4 = new Random();
We need to convert our generated number in an IP String
String ip1 = Integer.toString(b1); String ip2 = Integer.toString(b2); String ip3 = Integer.toString(b3); String ip4 = Integer.toString(b4);
The numbers generated may be higher than 255 hence we use String to IP converter which keeps the value 0 to 255 because the IPv4 has the limit of 0 to 255 only .
String b1 = IpConverter.longToIp(r1.nextLong()); String b2 = IpConverter.longToIp(r2.nextLong()); String b3 = IpConverter.longToIp(r3.nextLong()); String b4 = IpConverter.longToIp(r4.nextLong());
Now we Append the converted individual string and return it as the single IP address
sb = new StringBuilder(); sb.append(ip1).append(".").append(ip2).append(".").append(ip3).append(".").append(ip4); return sb.toString();And You Have Done :)
is this code run properly?
ReplyDeleteb1,b2,b3,b4 all are string . so Integer.toString(b1) run ?
Great collection and thanks for sharing this info with us. Waiting for more like this.
ReplyDeleteVMware Training in Chennai
VMware Training institute in chennai
Cloud Training in Chennai
Cloud Computing Courses in Chennai
Azure Training in Chennai
Microsoft Azure Training in Chennai
DevOps course in Chennai
VMware Training in Velachery
Cloud computing Training in Anna Nagar
I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.
ReplyDeleteGreat post keep on posting
Microsoft Windows Azure Training | Online Course | Certification in chennai | Microsoft Windows Azure Training | Online Course | Certification in bangalore | Microsoft Windows Azure Training | Online Course | Certification in hyderabad | Microsoft Windows Azure Training | Online Course | Certification in pune