2015年8月6日 星期四

[Android] ping SubNet

 private static final int NB_THREADS = 10;  
      String LOG_TAG = "go";  
      public void doScan(String subnet) {  
           Log.i(LOG_TAG, "Start scanning");  
           ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);  
           for (int dest = 0; dest < 255; dest++) {  
                String host = subnet + "." + dest;  
                executor.execute(pingRunnable(host));  
           }  
           Log.i(LOG_TAG, "Waiting for executor to terminate...");  
           executor.shutdown();  
           try {  
                executor.awaitTermination(60 * 1000, TimeUnit.MILLISECONDS);  
           } catch (InterruptedException ignored) {  
           }  
           Log.i(LOG_TAG, "Scan finished");  
      }  
      private Runnable pingRunnable(final String host) {  
           return new Runnable() {  
                public void run() {  
                     try {  
                          InetAddress inet = InetAddress.getByName(host);  
                          boolean reachable = inet.isReachable(1000);  
                          // if (reachable)  
                          {  
                               Log.d(LOG_TAG, "Pinging " + host + "...=> Result: " + reachable);  
                               // Log.d(LOG_TAG, "=> Result: " + (reachable ?  
                               // "reachable" : "not reachable"));  
                          }  
                     } catch (UnknownHostException e) {  
                          Log.e(LOG_TAG, "Not found", e);  
                     } catch (IOException e) {  
                          Log.e(LOG_TAG, "IO Error", e);  
                     }  
                }  
           };  
      }  

沒有留言:

張貼留言