java ping是什么,让我们一起了解一下?
ping命令是在项目中需要判断目录服务器是否在线,调研有两种方法:使用Java API的InetAddress方式,使用Runtime.exec调用操作系统的命令CMD。
Java实现ping功能的三种方法是什么?
1、Jdk1.5的InetAddresss方式:使用时应注意,如果远程服务器设置了防火墙或相关的配制,可能会影响到结果。另外,由于发送ICMP请求需要程序对系统有一定的权限,当这个权限无法满足时, isReachable方法将试着连接远程主机的TCP端口 7(Echo)。
2、最简单的办法,直接调用CMD:见Ping类的ping02(String)函数。
3、Java调用控制台执行ping命令:具体调用dos命令用Runtime.getRuntime().exec实现,查看字符串是否符合格式用正则表达式实现。
Java如何实现Ping命令?
通过Runtime.exec方法来调用本地CMD命令来执行以上语句,代码如下:
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** * @author tgg */
public class Ping {
public static boolean ping(String ipAddress) throws Exception {
int timeOut = 3000 ;
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
return status;
}
public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
// 将要执行的ping命令,此命令是windows格式的命令
String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
// Linux命令如下
// String pingCommand = "ping" -c " + pingTimes + " -w " + timeOut + ipAddress;
try {
if (logger.isDebugEnabled()) {
logger.debug(pingCommand);
}
// 执行命令并获取输出
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int connectedCount = 0;
String line;
// 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
}
// 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
return connectedCount == pingTimes;
} catch (Exception e) {
logger.error(e);
return false;
} finally {
try {
in.close();
} catch (IOException e) {
logger.error(e);
}
}
}
//若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return 1;
}
return 0;
}
private static final Logger logger = Logger.getLogger(Ping.class);
}以上就是小编今天的分享了,希望可以帮助到大家。