zoukankan      html  css  js  c++  java
  • 判断网络是否连通

    package com.adao.test.netping;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.InetAddress;
    import java.net.URL;
    
    public class InetJavaTest {
        private static String remoteInetAddr = "39.156.69.79";// 需要连接的IP地址
    
        /**
         * 传入需要连接的IP,返回是否连接成功
         * 
         * @param remoteInetAddr
         * @return
         */
        public static boolean isReachable(String remoteInetAddr) {
            boolean reachable = false;
            try {
                InetAddress address = InetAddress.getByName(remoteInetAddr);
                reachable = address.isReachable(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return reachable;
        }
    
        // linux
    //    public static final boolean isNodeReachable(String hostname) {
    //        try {
    //            return 0==Runtime.getRuntime().exec("ping -c 1 "+hostname).waitFor();
    //        } catch (InterruptedException | IOException e) {
    //            e.printStackTrace();
    //            return false;
    //        }
    //    }
    
        public static void main(String[] args) {
            URL url = null;
            Boolean bon = false;
    //        Boolean bon1 = false;
            try {
                url = new URL("http://baicu.com/");
                InputStream in = url.openStream();// 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
                System.out.println("连接正常");
                in.close();// 关闭此输入流并释放与该流关联的所有系统资源。
            } catch (IOException e) {
                System.out.println("无法连接到:" + url.toString());
            }
            bon = isReachable(remoteInetAddr);
    //        bon1 = isNodeReachable(remoteInetAddr);
    
            System.out.println("pingIP:" + bon);
        }
    }

     完美

  • 相关阅读:
    正则表达式
    scrollTop
    css3
    错误整理
    jquery-2
    vscode_修改字体,使用Fira Code
    实例_一个循环嵌套函数
    js_getComputed方法和style属性关于读取样式的区别
    html_html5增强的文件上传域_使用FileReader读取文件内容
    html_html5增强的文件上传域_FileList对象与File对象
  • 原文地址:https://www.cnblogs.com/adao21/p/13150794.html
Copyright © 2011-2022 走看看