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);
        }
    }

     完美

  • 相关阅读:
    CSS&JS两种方式实现手风琴式折叠菜单
    MySQL创建数据库/表等基本命令操作
    web注册功能实现
    符合altium designer操作习惯的cadence快捷键设置
    运行Capture.exe找不到cdn_sfl401as.dll
    modelsim遇到的问题(更新)
    1.4 扩展
    1.3 Security
    1.2 Install Extension 安装扩展
    1.1 Modify Template修改模板
  • 原文地址:https://www.cnblogs.com/adao21/p/13150794.html
Copyright © 2011-2022 走看看