如何在Java中使用ICMP和traceroutes

Ric*_*rdo 6 java sockets traceroute icmp

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

car*_*ott 5

这是我今天写的用 Java 来“实现”跟踪路由命令的内容。我只在 Windows 中进行了测试,但它应该也可以在 Linux 中工作,尽管有几个可用于 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 条件应更改为 os.toLowerCase().contains("win") (2认同)