Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

ip - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...