如何在Java中使用ICMP和traceroutes

Java没有ICMP和traceroute的原语。 怎么克服这个? 基本上我正在构建应该在* nix和Windows中运行的代码,并且需要一段将在两个平台上运行的代码。

以下是我今天在Java中“实现”trace route命令所写的内容。 我只在Windows中进行了测试,但它也适用于Linux,尽管有几种可用于Linux的traceroute工具,因此很可能需要对这些程序的存在进行一些检查。

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

您将需要jpcap库 (也许SourceForge jpcap也在工作)并使用ICMPPacket类来实现所需的function。

这是使用jpcap库的Java traceroute实现 。