-2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483

1 Answers1

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);
}

Source: https://stackoverflow.com/a/5711150/1688441

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