java ping ip地址

  1. **   
  2.      * 能否ping通IP地址   
  3.      * @param server IP地址   
  4.      * @param timeout 超時時長   
  5.      * @return true能ping通   
  6.      */   
  7.     public static boolean pingServer(String server, int timeout) {   
  8.         BufferedReader in = null;   
  9.         Runtime r = Runtime.getRuntime();   
  10.   
  11.         String pingCommand = "ping " + server + " -n 1 -w " + timeout;   
  12.         try {   
  13.             Process p = r.exec(pingCommand);   
  14.             if (p == null) {   
  15.                 return false;   
  16.             }   
  17.             in = new BufferedReader(new InputStreamReader(p.getInputStream()));   
  18.             String line = null;   
  19.             while ((line = in.readLine()) != null) {   
  20.                 if (line.startsWith("Reply from")) {   
  21.                     return true;   
  22.                 }   
  23.             }   
  24.   
  25.         } catch (Exception ex) {   
  26.             ex.printStackTrace();   
  27.             return false;   
  28.         } finally {   
  29.             try {   
  30.                 in.close();   
  31.             } catch (IOException e) {   
  32.                 e.printStackTrace();   
  33.             }   
  34.         }   
  35.         return false;   
  36.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章