7

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.

Kara
  • 5,650
  • 15
  • 48
  • 55
Ricardo
  • 1,321
  • 4
  • 14
  • 24

2 Answers2

4

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;
}
carlin.scott
  • 3,719
  • 2
  • 19
  • 27
  • 2
    The condition should be changed to os.toLowerCase().contains("win") – Hassan Sep 12 '15 at 02:59
  • where you used **convertStreamToString** method? – Omore Jan 25 '18 at 19:26
  • @Omore are you asking where it's defined? I think that's a custom method I wrote. I don't have access to the code anymore so you'll have to figure out how to implement it. If you do, please update my answer to include it; you'll get points for doing that. – carlin.scott Jan 26 '18 at 18:10
  • There a different ways to implement **convertStreamToString**: https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string – torno Mar 06 '18 at 12:47
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 .

bebbo
  • 2,357
  • 1
  • 24
  • 33
  • Did anybody manage to implement it using libpcap JNI libraries? I checked jpcap and pcap4j and both are not supposed to be used by humans :-( You need to have PhD to use them properly. And they are developed not for Java devs, no instructions for usage in Java environments. – nickolay.laptev Oct 24 '19 at 13:34