我有一个用Java编写的客户端-服务器项目,它们通过套接字连接。我无法弄清楚如何从Java代码的服务器端运行“ netstat”。
不幸的是,在Java中没有直接可用的netstat等效项。
您可以使用流程API生成新流程并检查输出。
我将使用以下问题的示例:https://stackoverflow.com/a/5711150/1688441
我已将其更改为呼叫netstat
。产生该过程之后,您还必须读取输出并进行解析。
Runtime rt = Runtime.getRuntime();
String[] commands = {"netstat", ""};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}