如何从Java程序运行Linux命令“ netstat”?

问题描述 投票:0回答:1

我有一个用Java编写的客户端-服务器项目,它们通过套接字连接。我无法弄清楚如何从Java代码的服务器端运行“ netstat”。

java linux server-side serversocket
1个回答
1
投票

不幸的是,在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);
}

来源:https://stackoverflow.com/a/5711150/1688441

© www.soinside.com 2019 - 2024. All rights reserved.