java ping window 和 linux

public String addPingForm() throws IOException {
   Runtime runtime = Runtime.getRuntime(); // 获取当前程序的运行进对象
  
   String osName = System.getProperty("os.name").toLowerCase();
  
   Process process = null; // 声明处理类对象
   if(osName.indexOf("windows") >= 0) {
        
     String line = null; // 返回行信息
     InputStream is = null; // 输入流
     InputStreamReader isr = null; // 字节流
     BufferedReader br = null;
    // String ip = "www.baidu.com";
     boolean res = false;// 结果
     try {
     
      process = runtime.exec("ping " + ipName); // PING
     
      is = process.getInputStream(); // 实例化输入流
      isr = new InputStreamReader(is);// 把输入流转换成字节流
      br = new BufferedReader(isr);// 从字节中读取文本
      while ((line = br.readLine()) != null) {
       if (line.contains("TTL")) {
        res = true;
        break;
       }
      }
      is.close();
      isr.close();
      br.close();
     
       if (res) {      
         setTip("ping 通  ...");
       } else {     
         setTip("ping 不通...");
       }
      
     } catch (IOException e) {
     e.printStackTrace();
     
     }
   
   }else{        
      process = Runtime.getRuntime().exec("ping -c 2 "+ipName);//ping 2次
         
           InputStreamReader r = new InputStreamReader(process.getInputStream()); 
           LineNumberReader returnData = new LineNumberReader(r); 
    
           String returnMsg=""; 
           String line = "";
           
      while ((line = returnData.readLine()) != null) {           
           returnMsg += line;                   
      }
     
      if(returnMsg.contains("ttl") || returnMsg.contains("TTL") ){ 
        setTip("ping 通 ...");
       }else{ 
        setTip("ping 不通 ...");
       }   
                           
      if(returnData != null){returnData.close(); }    
     
      if(r != null){ r.close(); }               
    
   }
  
  
  
  return SUCCESS;
 }

相关推荐