1

I want to check if a port is being used or not. I've used the command: netstat -an | grep <port_no> | grep -i listen. When I compare its output by running, if(message_port_check.equals(null)), it always returns null. How do I know if the port is open or not ?

This is what I've tried,

String port_no = textField_3.getText().toString();
String[] command_port = {
"/bin/sh",
"-c",
"netstat -an | grep " + port_no + " | grep -i listen"
};


try {

    ProcessBuilder builder = new ProcessBuilder(command_port);
    builder.redirectErrorStream(true);
    Process p = builder.start();

    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while (true) 
    {

        buffer.append(line).append("\n");
        line = r.readLine();
        if (line == null) { break; }
    }
    message_port= buffer.toString();
    p.waitFor();
    r.close();

} 

catch (IOException e1) 
{
    e1.printStackTrace();
} 

catch (InterruptedException e1) 
{
    e1.printStackTrace();
}

if(message_port_check.equals(null))
    rdbtn_port_free.setSelected(true);

else
    rdbtn_port_notfree.setSelected(true);
Pravar
  • 53
  • 2
  • 11

2 Answers2

2

I'd use -z test:

$ output=$(netstat -an | grep your_port | grep -i listen)
$ if [ -z "$output" ] ; then echo empty ; fi
empty
mauro
  • 5,730
  • 2
  • 26
  • 25
  • I tried using `if then echo`, it didn't work! I also tried to run your command, but it says `output: command not found`. For every possible variable name, I am having the same issue. – Pravar Jun 21 '17 at 10:53
  • @Pravar... strange. Please double check there are NO spaces around the equal sign. Just cut & paste my command here above excluding the initial dollar sign – mauro Jun 21 '17 at 11:33
  • Yeah, that was the issue! I had put spaces around the equal sign! Will try to resolve the error using your help! Thanks! – Pravar Jun 21 '17 at 11:55
1

You could use nc instead as shown in this reply. Then you just need to check the return value.

Of course in Java, the solution in the platform-independent spirit would be to try to connect/bind to the port using the standard library instead of relying on external Linux binaries. Some variants are shown here.

C. Ramseyer
  • 2,322
  • 2
  • 18
  • 22