How to ICMPs and traceroutes in Java

吃可爱长大的小学妹 提交于 2019-11-27 06:20:31

问题


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.


回答1:


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.

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



回答2:


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

Here is the Java traceroute implementation using the jpcap library .



来源:https://stackoverflow.com/questions/2627706/how-to-icmps-and-traceroutes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!