I want to run netstat -an | grep 12345
and retrieve the output to find out if a port is empty and ready to use. I have tried
TRY1:
System.out.println("RUNNING ==> "+command);
try
{
Process process = Runtime.getRuntime().exec("netstat -an | grep 4324");
InputStream in = process.getInputStream();
File tmp = File.createTempFile("allConnections","txt");
byte[] buf = new byte[256];
OutputStream outputConnectionsToFile = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = in.read(buf, 0, 256)) != -1)
{
outputConnectionsToFile.write(buf, 0, numbytes);
}
System.out.println("File is present at "+tmp.getAbsolutePath());
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
i see 12k results, like i was doing netstat -an
without grep
TRY2:
public static ArrayList<String> exec_command_dont_wait(String command) throws IOException, InterruptedException
{
//String[] arrayExplodedArguments = command.split(" ");
ArrayList<String> returnHolder = new ArrayList<String>();
List<String> listCommands = new ArrayList<String>();
String[] arrayExplodedCommands = command.split(" ");
for(String element : arrayExplodedCommands)
{
listCommands.add(element);
System.out.println(element+"\n");
}
System.exit(0);
ProcessBuilder ps = new ProcessBuilder(listCommands);
ps.redirectErrorStream(true);
Process p = ps.start();
BufferedReader buffer = new BufferedReader(new InputStreamReader(p.getInputStream()));
//p.waitFor();
String line = new String();
while((line = buffer.readLine()) != null)
{
returnHolder.add(line);
//System.out.println(line);
}
return returnHolder;
}
i see 12k results, like i was doing netstat -an
without grep
, never to mention that i have to comment //p.waitFor();
and i don't know why.
- How do i a simple
netstat
command withgrep
and retrieve the results? - Is there a simple command/function like in
PHP
and retrieve the results? Like 'exec()', really love that function. - What is the differance between running with
p.waitFor()
and without it. I mean i understand thatJAVA
waits for the process to finsish, butnetstat
seems to never finish, i waited 2 minutes. A simplecurl
finishes quicly.
Example
netstat -an | grep 4352
tcp 0 0 192.99.3.11:43529 118.32.42.29:22 ESTABLISHED
tcp 0 0 192.99.3.11:43522 15.139.118.57:22 ESTABLISHED
tcp 0 0 192.99.3.11:43521 116.322.199.10:22 ESTABLISHED
Thank you.