Posted By

bmvakili on 05/21/09


Tagged

pingrandom


Versions (?)

pinger


 / Published in: Java
 

URL: http://snipplr.com/

Requires: Java + Unix "Ping" Program + Root Access to Ping Program Description: Takes 1 argument, which is the number of random IP Adrresses to ping to. It pings each address 1 time with a timeout of 3 seconds. It only displays the ping information when successful, otherwise just displays ".".

  1. import java.io.*;
  2.  
  3. public class Pinger{
  4.  
  5. public static void main(String[] args){
  6.  
  7. int iter = 100;
  8. if(args.length>0){
  9. try{
  10. iter = Integer.parseInt(args[0]);
  11. }
  12. catch(Exception e){
  13. iter = 100;
  14. }
  15. }
  16. java.util.Random num = new java.util.Random();
  17. String host = "";
  18. int[] subs = new int[4];
  19. for(int i = 0; i < iter; i++){
  20. host="";
  21. for(int j = 0; j < 4; j++){
  22.  
  23. subs[j] = num.nextInt(255);
  24.  
  25. }
  26.  
  27. host = subs[0]+"."+subs[1]+"."+subs[2]+"."+subs[3];
  28. ping(host);
  29.  
  30. }
  31.  
  32. }
  33.  
  34. public static void ping(String host){
  35.  
  36. try {
  37. Process ping = Runtime.getRuntime().exec("ping -c 1 -t 3 " + host);
  38. BufferedReader br = new BufferedReader(new InputStreamReader(ping.getInputStream()));
  39. StringBuilder sb = new StringBuilder();
  40. String line;
  41. while ((line = br.readLine()) != null) {
  42. sb.append(line);
  43. sb.append("\n");
  44. }
  45. if(sb.toString().matches(".*0% packet loss.*")){
  46. System.out.println("\nTesting ping "+host+"...");
  47. System.out.print(sb.toString());
  48. }else{
  49. System.out.print(".");
  50. }
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54.  
  55. }
  56. }

Report this snippet  

You need to login to post a comment.