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

2 Answers 2

2

I'd use -z test:

$ output=$(netstat -an | grep your_port | grep -i listen)
$ if [ -z "$output" ] ; then echo empty ; fi
empty
Sign up to request clarification or add additional context in comments.

3 Comments

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... strange. Please double check there are NO spaces around the equal sign. Just cut & paste my command here above excluding the initial dollar sign
Yeah, that was the issue! I had put spaces around the equal sign! Will try to resolve the error using your help! Thanks!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.