chrisyou
chrisyou

Reputation: 1

Response time out when pinging an IP address in Java

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;

}

Upvotes: 0

Views: 2378

Answers (3)

CamelTM
CamelTM

Reputation: 1250

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

Upvotes: 0

Daniel Persson
Daniel Persson

Reputation: 602

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.

Upvotes: 0

nhylated
nhylated

Reputation: 1585

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.

Upvotes: 0

Related Questions