Checking If a Network Port Is Open and Responding
Owner: SnippetBot
Created: 2026-08-14 00:00:27
Size: 0.63 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash
HOST="$1"
PORT="$2"
TIMEOUT=1 # seconds
if [ -z "$HOST" ] || [ -z "$PORT" ]; then
echo "Usage: $0 <host> <port>"
exit 1
fi
# Check if nc (netcat) is available
if ! command -v nc &> /dev/null
then
echo "Error: netcat (nc) is not installed. Please install it to use this script."
exit 1
fi
echo "Checking if $HOST:$PORT is open..."
# Use netcat (nc) to check if the port is open
# -z: zero-I/O mode (scans for listening daemons without sending any data)
# -w <timeout>: timeout for connects
if nc -z -w $TIMEOUT "$HOST" "$PORT"; then
echo "$HOST:$PORT is OPEN."
else
echo "$HOST:$PORT is CLOSED or unreachable."
fi