java 在Win或liunx ping ip地址看是否可以ping通

发布时间:2024年01月05日

话不多说直接上代码

class text{
    public static void main(String[] args) {
         boolean isSuccess = ping("192.168.1.218");
    }

     private boolean ping(String ip) {
        log.info("ping ip:" + ip);
        //os:1-windows、2-linux
        int os = 2;

        BufferedReader in = null;
        Runtime r = Runtime.getRuntime();

        String pingCommand = "";
        String pingCommand1 = "ping " + ip + " -n 5 -w 10";
        String pingCommand2 = "ping " + ip + " -c 5 -W 10";
        if (os == 1) {
            pingCommand = pingCommand1;
        } else {
            pingCommand = pingCommand2;
        }

        try {
            Process p = r.exec(pingCommand);
            if (p == null) {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));

            int connectedCount = 0;
            String line = null;
            while ((line = in.readLine()) != null) {
                log.info("line:" + line);
                connectedCount += getCheckResult(line);
            }
            log.info("count:" + connectedCount);
            return (connectedCount >= 1);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private int getCheckResult(String line) {
        if ((line.contains("ttl=") || line.contains("TTL=")) && line.contains("ms")) {
            return 1;
        }
        return 0;
    }
}
 

有帮助的话记得点赞收藏

文章来源:https://blog.csdn.net/lailailaiww/article/details/135379340
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。