Here's what I wrote today to "implement" the trace route command in Java. I've only tested in windows but it should work in Linux as well although there are several traceroute tools available for Linux so most likely there need to be some checks for the existence of those programs.
public class NetworkDiagnostics{
private final String os = System.getProperty("os.name").toLowerCase();
public String traceRoute(InetAddress address){
String route = "";
try {
Process traceRt;
if(os.contains("win")) traceRt = Runtime.getRuntime().exec("tracert " + address.getHostAddress());
else traceRt = Runtime.getRuntime().exec("traceroute " + address.getHostAddress());
// read the output from the command
route = convertStreamToString(traceRt.getInputStream());
// read any errors from the attempted command
String errors = convertStreamToString(traceRt.getErrorStream());
if(errors != "") LOGGER.error(errors);
}
catch (IOException e) {
LOGGER.error("error while performing trace route command", e);
}
return route;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…