I have a client-server project written in Java in which they connect through sockets. I cannot figure out how to run “netstat” from the server side of my Java code.
Asked
Active
Viewed 1,074 times
-2
-
take a look at https://stackoverflow.com/questions/26830617/running-bash-commands-in-java – Andrew Lohr Feb 04 '20 at 21:51
-
For what purpose? You shouldn't need this. – user207421 Feb 04 '20 at 22:09
1 Answers
1
Unfortunately there is no netstat equivalent available directly in java.
You could use the process API to spawn a new process and check the output.
I will use an example from the following q/a: https://stackoverflow.com/a/5711150/1688441
I have changed it to call netstat
. After spawning the process you will also have to read the output and parse it.
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);
}

Menelaos
- 23,508
- 18
- 90
- 155
-
This doesn't work in the general case. You either need to merge the streams or read them concurrently in separate threads. – user207421 Feb 06 '20 at 09:39
-
@user207421 You're right!, as long as the process is running the first while loop will block the other. I'll update this. – Menelaos Feb 06 '20 at 09:42