Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ping value in java

I know that this question has been approached under different ways, but I have checked stackoverflow and I didn't found the answer I was looking for.

To make it simple : Is there a way to get the Time ping value to an IP server under Windows ?

I know how to check if some servers are reachable, but I would like to have precise values, like we can read on terminal.

Thank you for your help and understanding.

like image 299
user1614914 Avatar asked Feb 20 '23 10:02

user1614914


1 Answers

You can do something like this :

//The command to execute
String pingCmd = "ping " + ip + " -t";

//get the runtime to execute the command
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(pingCmd);     

//Gets the inputstream to read the output of the command
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

//reads the outputs
String inputLine = in.readLine();
while ((inputLine != null)) {
    if (inputLine.length() > 0) {
       ........
    }
    inputLine = in.readLine();
}

reference

UPDATE: As per your need

public class PingDemo {    
    public static void main(String[] args) {
        String ip = "localhost";
        String time = "";

        //The command to execute
        String pingCmd = "ping " + ip;

        //get the runtime to execute the command
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec(pingCmd);

            //Gets the inputstream to read the output of the command
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

            //reads the outputs
            String inputLine = in.readLine();
            while ((inputLine != null)) {
                if (inputLine.length() > 0 && inputLine.contains("time")) {
                     time = inputLine.substring(inputLine.indexOf("time"));
                     break;                        
                }
                inputLine = in.readLine();
            }    
            System.out.println("time --> " + time);    
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

Written in little haste.

like image 167
Harmeet Singh Avatar answered Feb 27 '23 11:02

Harmeet Singh