java通過ping 判斷網絡是否正常


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

 


免責聲明!

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



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