gpt4 book ai didi

java - 为什么我的 java ping 方法只在我的电脑上有效? (Windows机器已测试)

转载 作者:行者123 更新时间:2023-12-01 06:19:52 25 4
gpt4 key购买 nike

我用 Java 编写了以下 ping 函数供 Windows 使用,它在我自己的计算机上完美运行。不幸的是,我不知道为什么,但在其他计算机(Windows 机器)上,当我运行它时,它返回“null”

这是否会被 Windows 防火墙阻止?会不会是Windows版本的问题?从XP到windows8,还是不同的语言版本?

在我的计算机上,我收到这样的结果:time=19ms TTL=111

有人可以告诉我为什么会失败吗?

 private String ping() {

String ip = "<external IP of a server running, always online>";
String time = null;
String pingCommand = "ping " + ip;
ProcessBuilder builder = new ProcessBuilder(new String[] {"cmd.exe", "/C",pingCommand});
try {
Process newProcess = builder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(newProcess.getInputStream()));
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0) {
if(inputLine.contains("time")){
// Checking for the time only
time = inputLine.substring(inputLine.indexOf("time"));
break;
}
}
inputLine = in.readLine();
}
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return time;
}

最佳答案

您可以使用Runtime类来运行Windows命令。请参阅此示例;

   private String ping() {
Runtime rt = Runtime.getRuntime();
String time = null;
String pingCommand = "cmd.exe /C ping yourIpAddress";
try {
Process newProcess = rt.exec(pingCommand);
BufferedReader in = new BufferedReader(new InputStreamReader(
newProcess.getInputStream()));
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0) {
if (inputLine.contains("time")) {
// Checking for the time only
time = inputLine.substring(inputLine.indexOf("time"));
break;
}
}
inputLine = in.readLine();
}
} catch (IOException ex) {
}
return time;
}

关于java - 为什么我的 java ping 方法只在我的电脑上有效? (Windows机器已测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12316367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com