zoukankan      html  css  js  c++  java
  • 使用java检测网络连接状况

    windows中可以通过在cmd中使用ping命令来检测网络连接状况,如下:

    网络连接正常时:

    网络未连接时:

    在java中可以通过调用ping命令来判断网络是否连接正常:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    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());
     
        }
     
    }
  • 相关阅读:
    数论小结转载
    hdu 3792 二分
    求N的所有因子(约数)
    整数划分 --- 一个老生长谈的问题 动态规划
    hdu 1541 Stars poj 1195 Mobile phones(二维) poj 2155 Matrix(二维) hdu 3584 Cube(三维) 树状数组
    zoj 3175 Number of Containers
    asp.netMVC中权限控制论
    asp.net下使用Cookie保存登录信息
    asp.netMVC中实现分页方法
    asp.net异步上传
  • 原文地址:https://www.cnblogs.com/azhqiang/p/4548951.html
Copyright © 2011-2022 走看看