0

I am writing java application which gives me Port no. of application which is listening on particular port.

I want to get port no. of application which is listening on port 10001

Process p = Runtime.getRuntime().exec("lsof -i:10001 | awk '{print $2}'");
InputStream is=p.getInputStream();
byte b[]=new byte[is.available()];
is.read(b,0,b.length);
System.out.println(new String(b));
p.waitFor();
System.out.println("exit: " + p.exitValue());
p.destroy();

lsof -i:10001 | awk '{print $2}' when i execute this in shell it gets me output

PID
8092

But in java application it gives me exit: 1 . Why doesnt it run in java ? Also can i get just port no only ? i.e. instead of PID 8091 i want 8092

Shaggy
  • 5,422
  • 28
  • 98
  • 163

2 Answers2

1

try this

String[] cmd = { "/bin/sh", "-c", "lsof -i:10001 | awk '{print $2}'" };
Process p = Runtime.getRuntime.exec(cmd);

that is we run shell with -c option which means that the 3-rd param is shell script string

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

You can't use pipes in Runtime.exec directly (only by running a /bin/sh process and having it deal with the piping). A better approach might be to do just the lsof as an external process and then extract the second field in Java code rather than using awk.

Also note that the available() method returns a number of bytes that the stream knows it could give you right now without blocking, but that doesn't necessarily mean more bytes won't become available later. It is "never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream." (quote from InputStream JavaDoc). You need to keep reading until you hit EOF. Apache commons-io provides useful utility methods to help with this.

ProcessBuilder pb = new ProcessBuilder("lsof", "-i:10001");
pb.redirectError(ProcessBuilder.Redirect.to(new File("/dev/null")));
Process p = pb.start();
try {
  List<String> lines = IOUtils.readLines(p.getOutputStream());
  if(lines.size() > 1) {
    // more than one line, so the second (i.e. lines.get(1)) will have the info
    System.out.println(lines.get(1).split("\s+")[1]);
  } else {
    System.out.println("Nothing listening on port 10001");
  }
} finally {
  p.getOutputStream().close();
  p.waitFor();
}
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183