Thursday, October 6, 2022

[SOLVED] How to check if a connection can be made to a port in bash

Issue

I would like to check if I can connect to a port or not from within a bash script

Based on the answer to a similar href="https://stackoverflow.com/questions/4922943/test-if-remote-tcp-port-is-open-from-a-shell-script">question I tried running

nc -zvw10 <host> <port>

and check if the status code is 0/1

but many times it returns "Connection refused" and exits the script (there doesnt seem to be a return code)

I only want to exit the script if it returns a 0, which means a connection is made.


Solution

Use boolean operators:

#!/bin/bash
nc -zvw10 $1 $2 && exit 1 || echo "continue."
echo "It continues."

And on a closed port, it stops:

bash bar.sh localhost 2048
nc: connect to localhost port 2048 (tcp) failed: Connection refused
continue.
It continues.

So on open port:

bash bar.sh localhost 2049
Connection to localhost 2049 port [tcp/nfs] succeeded!


Answered By - Gaétan RYCKEBOER
Answer Checked By - Senaida (WPSolving Volunteer)