用Java实现TraceRT
、Ping
两个常用网络小工具,Windows和Linux都可以用
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
/**
* traceRTAndPing
*
* @author xiwh
*/
public class TracertAndPingUtil {
/**
* ping命令拼接
*
* @param ip
* @param packagenum 发送包数量
* @param overtime 超时时间
* @param packagelength 发送包长
*/
public void Ping(String ip, String packagenum, String overtime, String packagelength) {
String ping = "ping ";
// 拼接ping命令
//操作系统类型
String osName = System.getProperty("os.name").toUpperCase();
//编码
String codes = "GBK";
if (osName.contains("WINDOWS")) {
//-n 发送包数量 // -w超时时间(毫秒)// -l发送包长,最大65500
ping = ping + " -n " + packagenum + " -w " + overtime + " -l " + packagelength;
} else {
// -c发送包数量 // -i超时时间(秒)// -s发送包长,最大65500
ping = ping + " -c " + packagenum + " -i " + Float.parseFloat(overtime) / 1000.0 + " -s " + packagelength;
codes = "UTF-8";
}
ping = ping + " " + ip;
doPingOrTracert(ping, codes);
}
/**
* traceRT命令拼接
*
* @param ip
* @param maxnum 最大跃点数
* @param overtime 超时时间
*/
public List<String> Tracert(String ip, String maxnum, String overtime) {
// 拼接tracert命令
String tracert = "";
//操作系统类型
String osName = System.getProperty("os.name").toUpperCase();
//编码
String codes = "GBK";
// -h最大跃点数、-w超时时间
if (osName.contains("WINDOWS")) {
tracert = "tracert -d -h " + maxnum + " -w " + overtime + " " + ip;
} else {
//-m最大跃点数、-w超时时间
tracert = "traceroute -I -m " + maxnum + " -w " + Float.parseFloat(overtime) / 1000.0 + " " + ip;
codes = "UTF-8";
}
return doPingOrTracert(tracert, codes);
}
/**
* 执行命令并打印结果
*
* @param command 命令
* @param codes 编码
*/
public List<String> doPingOrTracert(String command, String codes) {
List<String> info = new LinkedList<>();
try {
// 通过Runtime类的getRuntime().exec()传入需要运行的命令参数
Process process = Runtime.getRuntime().exec(command);
// 定义用于接收命令行执行结果的字符串
String commandInfo = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), codes));
// 取出执行结果第一行空行
bufferedReader.readLine();
while ((commandInfo = bufferedReader.readLine()) != null) {
System.out.println(commandInfo);
// 逐行命令执行结果
info.add(commandInfo);
}
bufferedReader.close();
} catch (IOException exception) {
exception.printStackTrace();
}
return info;
}
public static void main(String[] args) {
TracertAndPingUtil util = new TracertAndPingUtil();
util.Ping("127.0.0.1", "5", "100", "32");
util.Tracert("baidu.com", "10", "500");
}
}
转载请注明出处:BestEternity亲笔。