【发布时间】:2020-02-04 21:47:27
【问题描述】:
我有一个用 Java 编写的客户端-服务器项目,它们通过套接字连接。我无法弄清楚如何从我的 Java 代码的服务器端运行“netstat”。
【问题讨论】:
-
出于什么目的?你不应该需要这个。
标签: java linux server-side serversocket
我有一个用 Java 编写的客户端-服务器项目,它们通过套接字连接。我无法弄清楚如何从我的 Java 代码的服务器端运行“netstat”。
【问题讨论】:
标签: java linux server-side serversocket
不幸的是,java 中没有直接可用的 netstat 等效项。
您可以使用进程 API 生成一个新进程并检查输出。
我将使用以下 q/a 中的示例: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);
}
【讨论】: