0

I have a task to make a simple console pinger in Java. I tried the following code and I have 2 main issues.

First of all even if I am connected to the internet (I can ping from console any site), when I run the code returns false.

Second, is it possible to track the time of response of the ping?

Here is the code:

try {
    InetAddress address = InetAddress.getByName(the_link);
    System.out.println(the_link);
    // Try to reach the specified address within the timeout
    // periode. If during this periode the address cannot be
    // reach then the method returns false.
    boolean reachable = address.isReachable(5000);
    System.out.println("Is host reachable? " + reachable);
} catch (Exception e) {
    e.printStackTrace();
}
Michaël
  • 3,679
  • 7
  • 39
  • 64
Vagelism
  • 601
  • 1
  • 16
  • 27

1 Answers1

1

This is not a good one to use for most external ips. Instead following can be used

boolean reachable = (java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.lk").waitFor()==0);
ironwood
  • 8,936
  • 15
  • 65
  • 114
  • This looks great but, I want to truck down the time of respondes. Can I do it with this command and save the times of mutliple pings to an array for example? – Vagelism Nov 26 '12 at 09:17
  • 1
    You can do the same thing with this also. Eg : You can add this to a thread and iterate it waiting for a desired time period. – ironwood Nov 26 '12 at 09:46
  • For the waiting I understand it , but I want to have the feedback of time? I want to grap the resault time that needed to ping and save it to a list. – Vagelism Nov 26 '12 at 09:59
  • 1
    That need to be checked. For an idea you can run BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(pingCmd).getInputStream())); and Check pingLine in while ((pingLine = bufferedReader.readLine()) != null) {}. – ironwood Nov 26 '12 at 11:37