使用java檢測網路連接狀況

來源:互聯網
上載者:User

標籤:

windows中可以通過在cmd中使用ping命令來檢測網路連接狀況,如下:

網路連接正常時:


網路未串連時:



在java中可以通過調用ping命令來判斷網路是否串連正常:

package module.system.common;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * 判斷網路連接狀況. * @author nagsh * */public class NetState {    public boolean isConnect(){    boolean connect = false;    Runtime runtime = Runtime.getRuntime();    Process process;try {process = runtime.exec("ping " + "www.baidu.com");InputStream is = process.getInputStream();         InputStreamReader isr = new InputStreamReader(is);         BufferedReader br = new BufferedReader(isr);         String line = null;         StringBuffer sb = new StringBuffer();         while ((line = br.readLine()) != null) {             sb.append(line);         }         System.out.println("傳回值為:"+sb);          is.close();         isr.close();         br.close();         if (null != sb && !sb.toString().equals("")) {             String logString = "";             if (sb.toString().indexOf("TTL") > 0) {                 // 網路暢通              connect = true;            } else {                 // 網路不暢通              connect = false;            }         } } catch (IOException e) {e.printStackTrace();}         return connect;    }public static void main(String[] args) {NetState netState = new NetState();System.out.println(netState.isConnect());}}







使用java檢測網路連接狀況

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.