BASH

Check if a Network Port is Open and Listening

Quickly verify if a specific network port on a server or localhost is open and actively listening, crucial for debugging network services.

#!/bin/bash

# Configuration
HOST="localhost" # Or an IP address / domain name
PORT="80" # Port to check (e.g., 22 for SSH, 80 for HTTP, 443 for HTTPS)

echo "Checking if ${HOST}:${PORT} is open and listening..."

# Use netcat (nc) to check if the port is open
# -z: zero-I/O mode (don't send any data)
# -w 1: timeout after 1 second
nc -zv "${HOST}" "${PORT}" 2>&1 | grep -q 'succeeded!'

if [ $? -eq 0 ]; then
  echo "Port ${PORT} on ${HOST} is OPEN."
  exit 0
else
  echo "Port ${PORT} on ${HOST} is CLOSED or NOT LISTENING."
  exit 1
fi
How it works: This script checks whether a specific network port on a given host is open and actively listening. It leverages the `nc` (netcat) utility with the `-z` (zero-I/O) and `-w` (timeout) options to attempt a connection. The output is then parsed to determine if the connection "succeeded!", indicating the port is open, or if it failed. This is invaluable for debugging network service availability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs