ping外网

  1. /** 
  2.      * @author suncat 
  3.      * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网) 
  4.      * @return 
  5.      */  
  6.     public static final boolean ping() {  
  7.   
  8.         String result = null;  
  9.         try {  
  10.                 String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网  
  11.                 Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次  
  12.                 // 读取ping的内容,可以不加  
  13.                 InputStream input = p.getInputStream();  
  14.                 BufferedReader in = new BufferedReader(new InputStreamReader(input));  
  15.                 StringBuffer stringBuffer = new StringBuffer();  
  16.                 String content = "";  
  17.                 while ((content = in.readLine()) != null) {  
  18.                         stringBuffer.append(content);  
  19.                 }  
  20.                 Log.d("------ping-----", "result content : " + stringBuffer.toString());  
  21.                 // ping的状态  
  22.                 int status = p.waitFor();  
  23.                 if (status == 0) {  
  24.                         result = "success";  
  25.                         return true;  
  26.                 } else {  
  27.                         result = "failed";  
  28.                 }  
  29.         } catch (IOException e) {  
  30.                 result = "IOException";  
  31.         } catch (InterruptedException e) {  
  32.                 result = "InterruptedException";  
  33.         } finally {  
  34.                 Log.d("----result---", "result = " + result);  
  35.         }  
  36.         return false;  
  37. }  
posted @ 2017-11-27 10:07  小毛驴  阅读(614)  评论(0编辑  收藏  举报