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