📄 javaping.java
字号:
package cnoss.pm.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* <p>Title: JavaPing.java</p>
* <p>Description: </p>
* <p>Copyright:OnewaveInc Copyright (c) 2007</p>
* <p>Company: OnewaveInc</p>
* @author Zhengrw
* @version 3.0
*/
public class JavaPing {
/**
* ping the server with defaut settings.
* @param server server to ping
* @return
*/
public static PingResult pingServer(String server){
return pingServer(server, 4, 3000);
}
/**
* ping the server
* @param server String server to ping
* @param times int ping times
* @param timeout int timeout
* @return boolean
* @throws IOException
*/
public static PingResult pingServer(String server,int times, int timeout) {
PingResult result = new PingResult();
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
String pingCommand = "ping " + server + " -n " + times + " -w " + timeout;
try {
Process p = r.exec(pingCommand);
if (p == null) {
return result;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
if (line.indexOf("Packets")!=-1) {
line = line.replaceAll("(\\(.*)|[^(\\d|,)]", "");
String[] allElements = line.split(",");
if(allElements.length == 3){
int sent = Integer.parseInt(allElements[0]);
int received = Integer.parseInt(allElements[1]);
int lost = Integer.parseInt(allElements[2]);
result.setSentPackets(sent);
result.setReceivedPackets(received);
result.setLostPackets(lost);
result.setLostPacketsRate(lost/sent);
}
}else if(line.indexOf("Minimum")!=-1){
line = line.replaceAll("[^(\\d|,)]", "");
String[] allElements = line.split(",");
if(allElements.length == 3){
result.setMinRoundTripTime(Long.parseLong(allElements[0]));
result.setMaxRoundTripTime(Long.parseLong(allElements[1]));
result.setAvgRoundTripTime(Long.parseLong(allElements[2]));
}
}
}
in.close();
} catch (Exception ex) {
return result;
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
PingResult result = JavaPing.pingServer("192.168.51.102");
System.out.println("丢包率:" + result.getLostPacketsRate() + "时延:" + result.getAvgRoundTripTime());
System.out.println("最大时延:" + result.getMaxRoundTripTime());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -