Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

sockets - How to ICMPs and traceroutes in Java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...