如何在Java中使用ICMP和跟踪路由
问题描述:
Java没有ICMP和跟踪路由的原语。如何克服这一点?基本上,我构建的代码应该在* nix和Windows中运行,并且需要一段可以在两个平台上运行的代码。如何在Java中使用ICMP和跟踪路由
答
这是我今天写的“实现”Java中的跟踪路由命令。我只在Windows上测试过,但它也应该在Linux中工作,尽管有几种traceroute工具可用于Linux,所以很可能需要对这些程序的存在进行一些检查。
public class NetworkDiagnostics{
private final String os = System.getProperty("os.name").toLowerCase();
public String traceRoute(InetAddress address){
String route = "";
try {
Process traceRt;
if(os.contains("win")) traceRt = Runtime.getRuntime().exec("tracert " + address.getHostAddress());
else traceRt = Runtime.getRuntime().exec("traceroute " + address.getHostAddress());
// read the output from the command
route = convertStreamToString(traceRt.getInputStream());
// read any errors from the attempted command
String errors = convertStreamToString(traceRt.getErrorStream());
if(errors != "") LOGGER.error(errors);
}
catch (IOException e) {
LOGGER.error("error while performing trace route command", e);
}
return route;
}
应将条件更改为os.toLowerCase()。contains(“win”) – Hassan 2015-09-12 02:59:00
您在哪里使用了** convertStreamToString **方法? – Omore 2018-01-25 19:26:29
@Omore你问问它在哪里定义?我认为这是我写的一种自定义方法。我再也无法访问代码,所以你必须弄清楚如何实现它。如果你这样做,请更新我的答案以包含它;你会得到这样的积分。 – 2018-01-26 18:10:10