首页 > 代码库 > java通过ping 判断网络是否正常

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 }  

 

java通过ping 判断网络是否正常