JAVA判斷網絡是否連通


 1 import java.io.BufferedReader;  2 import java.io.IOException;  3 import java.io.InputStream;  4 import java.io.InputStreamReader;  5      
 6 /**  
 7  * 判斷網絡連接狀況.  8  * @author 9  * @date 2019年3月25日 10  */   
11 public class PingIpUtil { 12     
13     /**
14  * 校驗是否可以連通 15  * @param ip 16  * @return true/false 17      */
18     public static boolean isConnect(String ip){ 19         boolean connect = false; 20         Runtime runtime = Runtime.getRuntime(); 21  Process process; 22         try { 23             process = runtime.exec("ping " + ip); 24             InputStream is = process.getInputStream(); 25             InputStreamReader isr = new InputStreamReader(is); 26             BufferedReader br = new BufferedReader(isr); 27             String line = null; 28             StringBuffer sb = new StringBuffer(); 29             while ((line = br.readLine()) != null) { 30  sb.append(line); 31  } 32  is.close(); 33  isr.close(); 34  br.close(); 35      
36             if (null != sb && !sb.toString().equals("")) { 37                 String logString = ""; 38                 if (sb.toString().indexOf("TTL") > 0) { 39                     // 網絡暢通 
40                     connect = true; 41                 } else { 42                     // 網絡不暢通 
43                     connect = false; 44  } 45  } 46         } catch (IOException e) { 47  e.printStackTrace(); 48  } 49         return connect; 50  } 51          
52     public static void main(String[] args) { 53         PingIpUtil netState = new PingIpUtil(); 54         System.out.println("ping結果:"+netState.isConnect("IP")); 55      
56  } 57 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM