Java Ping pingHost(String host)

Here you can find the source of pingHost(String host)

Description

ping Host

License

Open Source License

Declaration

public static int pingHost(String host) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static Pattern windowsLatencyPattern = Pattern.compile("Average = ([0-9]+)ms");

    public static int pingHost(String host) {
        try {/*from   w w w .  j  a  va  2  s  .  com*/
            String cmd = "";

            if (System.getProperty("os.name").startsWith("Windows")) {
                // For Windows
                cmd = "cmd /c ping " + host + " -n 1";
            } else {
                // For Linux and OSX
                cmd = "ping -c 1 " + host;
            }

            Process myProcess = Runtime.getRuntime().exec(cmd);
            myProcess.waitFor();

            if (myProcess.exitValue() == 0) {

                BufferedReader input = new BufferedReader(new InputStreamReader(myProcess.getInputStream()));

                String response = "";
                String line = "";

                while ((line = input.readLine()) != null) {
                    response += line;
                }

                return getLatencyWindows(response);

            } else {

                // FAILED
                return 0;

            }

        } catch (Exception e) {

            e.printStackTrace();
            return 0;
        }
    }

    private static int getLatencyWindows(String input) {

        Matcher matcher;
        String matchedValue;

        matcher = windowsLatencyPattern.matcher(input);

        if (matcher.find()) {

            // If successful, the ping command should return a string containing
            // the millisecond return time. For our purposes, we take the
            // average, as matched by the regular expression group.
            matchedValue = matcher.group(1);

            return Integer.parseInt(matchedValue);

        } else {
            throw new UnsupportedOperationException();
        }
    }
}

Related

  1. ping(String ip)
  2. ping(String url, int timeout)
  3. ping(String url, int timeout)
  4. pingHttp(URL url, int retry, int timeout)
  5. pingUrl(final String address)
  6. pingURL(final String url)
  7. pingUrl(String Url)