0

Here is what I use to ping an IPv4-Address and to record the actual response time in ms. Unfortunately I never get a valid response.. The request always times out. 0 is always returned. Please help :)

private long pingHost(String host, int port) {
    try {                   
        Inet4Address inet4 = (Inet4Address)InetAddress.getByName(host);         
        long start = System.currentTimeMillis();
        if(inet4.isReachable(5000)){
            long end = System.currentTimeMillis();
            long total = end-start;
            System.out.println(total);
            return total;
        }   

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;

}
Tim
  • 2,563
  • 1
  • 23
  • 31
chrisyou
  • 1
  • 1

3 Answers3

0

Create a process in Java and execute the ping command in it. The isReachable method is known to not work.

See this answer for more details and code examples.

Community
  • 1
  • 1
nhylated
  • 1,575
  • 13
  • 19
0

Have you tried with

isReachable(NetworkInterface netif, int ttl, int timeout) Test whether that address is reachable.

Your time to live might be to small so the connection never reaches the destination.

Daniel Persson
  • 602
  • 7
  • 17
0

May be use Socket? Something like this:

class PingTask implements Runnable {

    private int timeout;
    private Target target;// has InetSocketAddress field (getAddress()...)

    PingTask(Target target, int timeout) {
            this.target = target;
            this.timeout = timeout;
    }

    public String getHost() {
            return target.getAddress().getAddress() + ":" + target.getAddress().getPort();
    }

    @Override
    public void run() {
            Socket connection = new Socket();
            boolean reachable;
            long start = System.currentTimeMillis();
            try {
                    try {
                            connection.connect(target.getAddress(), timeout);
                    } finally {
                            connection.close();
                    }
                    long dur = (System.currentTimeMillis() - start);
                    System.out.printf("%5d ms %s%n", dur, target.getAddress().getHostString() );
                    reachable = true;
            } catch (Exception e) {
                    reachable = false;
            }

            if (!reachable) {
                    System.out.println(
                            String.format(
                                    "\t%s was UNREACHABLE",
                                    getHost()
                            )
                    );
            }
    } }
CamelTM
  • 1,225
  • 12
  • 17