如何在 Java 中使用 ICMP 和跟踪路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2627706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:05:53  来源:igfitidea点击:

How to ICMPs and traceroutes in Java

javasocketstracerouteicmp

提问by Ricardo

Java does not have primitives for ICMPs and traceroute. How to overcome this? Basically I'm building code that should run in *nix and Windows, and need a piece of code that will run in both platforms.

Java 没有用于 ICMP 和跟踪路由的原语。如何克服这一点?基本上我正在构建应该在 *nix 和 Windows 中运行的代码,并且需要一段可以在两个平台上运行的代码。

回答by carlin.scott

Here's what I wrote today to "implement" the trace route command in Java. I've only tested in windows but it should work in Linux as well although there are several traceroute tools available for Linux so most likely there need to be some checks for the existence of those programs.

这就是我今天写的在 Java 中“实现”trace route 命令的内容。我只在 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;
}

回答by bebbo

You'll need the jpcap library (maybe the SourceForge jpcapis working too) and use the ICMPPacket class to implement the desired functionality.

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

Here is the Java traceroute implementationusing the jpcap library .

这是使用jpcap 库Java traceroute 实现