BASH
Checking if a TCP Port is Listening for Service Availability
Utilize this Bash snippet to quickly verify if a specific TCP port is actively listening on a host, crucial for checking web server or database service availability and diagnostics.
#!/bin/bash
HOST="localhost"
PORT="80" # Example: HTTP port
echo "Checking if $HOST:$PORT is listening..."
if nc -z -w 1 "$HOST" "$PORT" &>/dev/null; then
echo "$HOST:$PORT is listening."
exit 0
else
echo "$HOST:$PORT is not listening."
exit 1
fi
How it works: This script uses `netcat` (`nc`) to check if a specific TCP port on a given host is open and listening. The `-z` flag performs a zero-I/O scan, and `-w 1` sets a timeout of 1 second, making it a quick and efficient way to determine service availability.