Java InetAddress Ping pingWindows(InetAddress address, long timeout)

Here you can find the source of pingWindows(InetAddress address, long timeout)

Description

ping Windows

License

Apache License

Declaration

private static long pingWindows(InetAddress address, long timeout) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.net.*;

public class Main {
    private static long pingWindows(InetAddress address, long timeout) {
        boolean reached = false;
        long start = System.currentTimeMillis();
        long end = (start - 1);

        try {/*  ww w . j  a v a 2 s  . co m*/
            String line;
            ProcessBuilder processBuilder = new ProcessBuilder(
                    new String[] { "ping", address.getHostAddress(), "-w", String.valueOf(timeout), "-n", "1" });
            Process process = processBuilder.start();

            int processing = 0;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {
                processing++;
                if (processing == 2) {
                    start = System.currentTimeMillis();
                }

                else if (processing == 3) {
                    if (line.contains(address.getHostAddress())) {
                        end = System.currentTimeMillis();
                    }
                }
            }

            if (calculatePingDelay(start, end) > timeout) {
                return calculatePingDelay(1, 0);
            }

            bufferedReader.close();
        } catch (IOException ex) {
            if (reached) {
                return calculatePingDelay(1, 0);
            }
        }

        return calculatePingDelay(start, end);
    }

    private static long calculatePingDelay(long start, long end) {
        return (end - start);
    }
}

Related

  1. ping(InetAddress addr, NetworkInterface ni)
  2. ping(InetAddress host)
  3. ping(InetAddress target)
  4. pingFromLocalAddress(InetAddress localAddr)
  5. pingUsingInetAddress()