Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 221
Ricardo Avatar asked Apr 13 '10 07:04

Ricardo


People also ask

How is ICMP used in traceroute?

A traceroute works by sending Internet Control Message Protocol (ICMP) packets, and every router involved in transferring the data gets these packets. The ICMP packets provide information about whether the routers used in the transmission are able to effectively transfer the data.

How do I ping and traceroute?

Run Ping and Tracert in Windows In the command line window that opens, type ping example.com, and hit Enter. Once the test is complete, type tracert example.com and hit Enter. Please copy and paste the results from both tests and send them to [email protected].

Is traceroute ICMP or TCP?

The regular traceroute usually uses either ICMP or UDP protocols. Unfortunately firewalls and routers often block the ICMP protocol completely or disallow the ICMP echo requests (ping requests), and/or block various UDP ports.

Is traceroute UDP or ICMP?

The traceroute command uses ICMP Time Exceeded messages to trace a network route. As discussed during IP, the Time to Live field is used to avoid routing loops: every time a packet passes through a router, the router decrements the TTL field.


2 Answers

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;
}
like image 178
carlin.scott Avatar answered Oct 05 '22 20:10

carlin.scott


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 .

like image 26
bebbo Avatar answered Oct 05 '22 20:10

bebbo