BASH

Check if a Port is in Use

A practical bash script to determine if a specific TCP port is currently being listened on, essential for debugging network issues or starting services.

#!/bin/bash

PORT_TO_CHECK="$1"

if [ -z "$PORT_TO_CHECK" ]; then
    echo "Usage: $0 <port_number>"
    exit 1
fi

if ! [[ "$PORT_TO_CHECK" =~ ^[0-9]+$ ]]; then
    echo "Error: Port must be a number."
    exit 1
fi

if [ "$PORT_TO_CHECK" -lt 1 ] || [ "$PORT_TO_CHECK" -gt 65535 ]; then
    echo "Error: Port number must be between 1 and 65535."
    exit 1
fi

# Check if the port is in use using netstat or lsof
# netstat -tuln | grep ":$PORT_TO_CHECK\\b" || lsof -i tcp:"$PORT_TO_CHECK"

if ss -tuln | grep -q ":$PORT_TO_CHECK\\b"; then
    echo "Port $PORT_TO_CHECK is in use."
    exit 0
else
    echo "Port $PORT_TO_CHECK is free."
    exit 1
fi
How it works: This script takes a port number as a command-line argument and checks if any process is listening on that TCP port. It uses the `ss -tuln` command (or `netstat -tuln` as an alternative) combined with `grep -q` to quietly search for the port. The script performs basic input validation for the port number and exits with status 0 if the port is in use and 1 if it's free, making it suitable for automated checks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs