Java代码中验证IP地址是否可访问【Linux和windows环境下】

个人博客:https:lingdu.love

Java代码中验证IP地址是否可访问【Linux和windows环境下】

我的需求场景是尝试连接数据源,数据库地址有不同网络环境下的地址{生产、内网、局域网等},所以在连接数据源之前判断一下url中的ip是否可访问,然后决定是否执行下一步操作。

提取字符串中的IP

	/**
     * 提取字符串中的IP集合
     * @param line 目标字符
     * @return 返回所有发现的IP
     * @作者 <b><a class=b href="https://blog.csdn.net/lingdu_dou" color="red">⭕°</a></b>
     * @创建时间 2022-08-30 11:20     */
    public static List<String> extractIp(String line) {
        List<String> ips = new ArrayList<>();
        if (line != null) {
            String regex = "(^|[^\\d])(((2[0-4]\\d|25[0-5]|1\\d\\d|\\d\\d?)\\.){3}(2[0-4]\\d|25\\d|1\\d\\d|\\d\\d?))";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(line);
            while (m.find()) {
                ips.add(m.group(2));
            }
        }
        return ips;
    }

检查是否可访问

	/**
     * 测试网址是否可访问
     * @param ip ip地址
     * @return 返回true可访问 返回false不可访问
     * @作者 <b><a class=b href="https://blog.csdn.net/lingdu_dou" color="red">⭕°</a></b>
     * @创建时间 2022-08-31 9:05     */
    public static boolean ping(String ip) {
        //获取操作系统类型
        String osName = System.getProperty("os.name");
        log.info("操作系统:"+osName);
        String command = "";
        if(osName.contains("Linux")){
            command = "ping -c 1 -w 1 "+ip;
        }else if(osName.contains("Windows")){
            command = "ping -n 1 -w 1000 "+ip;
        }else {
            log.error("未知系统 执行ping命令失败");
            return false;
        }
        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                if (line.contains("来自")||line.contains("1 received")) {
                    log.info(ip + " 连接成功");
                    return true;
                }
                if (line.contains("请求超时")||line.contains("0 received")) {
                    log.info(ip + " 连接失败");
                    return false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零〇°豆

今天快乐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值