All the Ways to Check If a Port is Open in Linux

Published:10 August 2022 - 8 min. read

Nicholas Xuan Nguyen Image

Nicholas Xuan Nguyen

Read more tutorials by Nicholas Xuan Nguyen!

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Your Linux server is running, and you now want to check if a specific port is open so that you can access it remotely. Checking for open ports is a fairly common task for system administrators, and there are a few different ways to do so in Linux.

In this article, you will learn several ways to check if a port is open in Linux so you may choose which ones work best for you. Ready? Read on!

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, ensure you have the following.

  • A Linux computer. This guide uses Ubuntu 20.04, but any recent Linux distribution should work.
  • Access to a terminal. If you use a graphical desktop environment, look for a terminal emulator program in your application menu. Or, if you logged into a remote server via SSH,
  • A user account with sudo privileges. For simplicity, this tutorial uses the root user.

Check If a Port is Open in Linux Using netstat

The first method to check if a port is open in Linux is by running the netstat command. This command displays network connections, routing tables, and many network interface statistics.

The netstat command is part of the net-tools package, and this package may not come by default with your Linux distro. On Ubuntu, install netstat by running the following commands in the terminal.

apt update -y && apt install net-tools -y

Suppose you have an NGINX web server running and want to check if port 80 is open. You can do so by running the following command. Replace 80 with the port number you wish to check.

The -tulpn flags instruct netstat to display all the listening ports. The first grep command finds and filters the line containing the word LISTEN in the result. The second grep command filters the results to display only those items matching :80.

netstat -tulpn | grep LISTEN | grep :80

To know more about the netstat flags, run the netstat –help command.

If the port is open, you will see the following output. As you can see, the output shows that port 80 is open on the system. tcp is the protocol type, and :::80 indicates that it’s a TCPv6 port. 0.0.0.0:80 means that the port is open for all IPv4 addresses. 80 is the default HTTP port serving access to the website.

Checking If a Port is Open with netstat
Checking If a Port is Open with netstat

Checking If a Port is Open Using ss

The ss command is another command-line utility for checking open ports. This command displays socket statistics, which you can use to confirm if a port is open or not. The ss command displays more information about open ports than the other tools.

Like the netstat command, the -t flag instructs ss to display only TCP sockets, -u to display only UDP sockets, and -l to show only listening sockets. The -p flag indicates the process name or PID using the port.

ss -tulpn | grep LISTEN | grep :80

You will see the following output if the port is open. As you can see, the output contains the process name and PID for each listening port. In this case, port 80 is open, and the NGINX web server is using it.

Checking If a Port is Open Using ss
Checking If a Port is Open Using ss

Checking If a Port is Open Using lsof

The lsof command is another handy tool to check for open ports. The lsof name stands for list open files, which displays information about files that are open on the system. This information includes file descriptors, process ids, user ids, etc.

How does listing open files help you determine if a port is open? You probably already heard the phrase “everything in Linux is a file,”— and this phrase means what it says.

For example, suppose you want to check if port 22 is open and your users can SSH into your server. Run the below command to list open files with active connections in port 22.

The -i flag instructs lsof to display all the open Internet sockets. The -P flag shows the port numbers instead of the service names. And the -n flag suppresses DNS and service name lookups, so you’ll see the IP addresses instead of the remote host names.

lsof -i -P -n | grep LISTEN | grep :22

If the port is open, you will see the following output. As you can see, the output contains information about:

  • 1027 is the process id of the sshd service.
  • root is the user id that is using the port.
  • 3u and 4u are the file descriptors for IPv4 and IPv6, respectively.
  • 31035 and 31037 are the network ports for IPv4 and IPv6, respectively.
  • :22 indicates that port 22 is open for all IPv4 and IPv6 addresses.
  • (LISTEN) shows that the port is listening for incoming connections.
  • 0t0 is the status of the socket, which means that the socket is in the LISTEN state.
Checking If a Port is Open Using lsof
Checking If a Port is Open Using lsof

Checking If a Port is Open Using nmap

So far, you have seen how to check if a port is open on Linux using the command line. But what if you want to check if a port is open on a remote machine? In that case, you can use the nmap tool.

But before running nmap, be aware that this tool may not be part of the default packages in your Linux distro. In which case, you must first install nmap by running the below command.

apt install nmap -y

Now, run the following command to check if a port is open on a remote machine. This command tests if port 22 is open on 159.89.176.25 so your user can SSH into your server. Replace the IP address as needed with yours.

nmap -p 22 159.89.176.25

As you can see, the output contains information about:

  • The port scanning start time (2022-06-30 16:58 UTC).
  • The IP address of the remote machine (159.89.176.25).
  • The state of the port (open).
  • The service that is using the port (ssh).
  • The state of the host (up).
Checking If a Port is Open Using nmap
Checking If a Port is Open Using nmap

The result confirms that users can SSH into the computer using the IP address and port.

ssh [email protected] -p 22

The screenshot below shows a successful SSH connection to the server, proving that port 22 is open.

SSHing into your server
SSHing into your server

Testing if a Port is Open from a Shell Script

Automation is always a good idea. Checking open ports by running a shell script is an excellent way to test multiple ports. You can use any previous methods to check if a port is open. But, for this example, you will be writing a basic shell script that runs the Netcat nc command.

1. Create a file named check_port.sh in your home directory using your preferred text editor. This example uses nano.

nano check_port.sh

2. Copy the below sample code into your editor. Replace 80 with the port number that you want to check.

The if condition checks if the 80 port is open using the nc command. The 2>&1 and >/dev/null redirect the error and output messages to /dev/null, respectively. The /dev/null is a special file that discards everything it receives.

If the port is open, the check_port.sh script will print Online to the console. Else, the script will print Offline.

if ( nc -zv localhost 80 2>&1 >/dev/null ); then
    echo 'Online'
else
    echo 'Offline'
fi

The script file should look similar to the below screenshot. Save the script and exit the editor.

Creating the Shell script
Creating the Shell script

3. Run the shell script to start checking for the open ports you specified inside the script.

bash check_port.sh

You will see one of the following outputs depending on whether the port is open. In this case, the port is open, which the message Online confirms.

Check if the 80 port is open
Check if the 80 port is open

You can use this shell script to check if a port is open at an interval or a scheduled job. Scripting is especially helpful when you have to check multiple servers. You only need to copy this check_port.sh script to all the servers you want to check and run it using CI/CD tools such as Jenkins or Ansible.

Testing If a Port is Open Using PowerShell

PowerShell has a built-in cmdlet for testing network connections called Test-NetConnection — but that cmdlet is only available on Windows systems. Don’t worry; you can still use PowerShell in Linux to check open ports and connections using the TcpClient class.

If your Linux computer does not have PowerShell yet, install it by following the instructions in this Microsoft documentation: Install PowerShell on Linux.

1. Launch PowerShell by running the below command.

pwsh
Launching PowerShell
Launching PowerShell

2. Next, create a file called Test-Port.ps1 using your text editor. This example uses nano.

nano Test-Port.ps1

3. Next, copy the below code into your editor. Save the file and exit the editor afterward.

Note: This code is an excerpt of the An All-in-One PowerShell Test Port Testing Tool.

<#
	.SYNOPSIS
		This function tests for open TCP/UDP ports.
	.DESCRIPTION
		This function tests any TCP/UDP port to see if it's open or closed.
	.NOTES

	.PARAMETER Computername
		One or more remote, comma-separated computer names
	.PARAMETER Port
		One or more comma-separated port numbers you'd like to test.
	.PARAMETER TcpTimeout
		The number of milliseconds that the function will wait until declaring
		the TCP port closed. Default is 1000.
	.EXAMPLE
		PS> Test-Port -Computername 'LABDC','LABDC2' -Protocol TCP 80,443
		
		This example tests the TCP network ports 80 and 443 on both the LABDC
		and LABDC2 servers.
	#>
[CmdletBinding()]
[OutputType([System.Management.Automation.PSCustomObject])]
param (
    [Parameter(Mandatory)]
    [string[]]$ComputerName,
    [Parameter(Mandatory)]
    [int[]]$Port,
    [Parameter()]
    [int]$TcpTimeout = 1000
)
begin {
    $Protocol = 'TCP'
}
process {
    foreach ($Computer in $ComputerName) {
        foreach ($Portx in $Port) {            
            $Output = @{ 'Computername' = $Computer; 'Port' = $Portx; 'Protocol' = $Protocol; 'Result' = '' }
            Write-Verbose "$($MyInvocation.MyCommand.Name) - Beginning port test on '$Computer' on port '$Protocol<code>:$Portx'"

            $TcpClient = New-Object System.Net.Sockets.TcpClient
            $Connect = $TcpClient.BeginConnect($Computer, $Portx, $null, $null)
            $Wait = $Connect.AsyncWaitHandle.WaitOne($TcpTimeout, $false)
            if (!$Wait -or !($TcpClient.Connected)) {
                $TcpClient.Close()
                Write-Verbose "$($MyInvocation.MyCommand.Name) - '$Computer' failed port test on port '$Protocol</code>:$Portx'"
                $Output.Result = $false
            }
            else {
                $TcpClient.EndConnect($Connect)
                $TcpClient.Close()
                Write-Verbose "$($MyInvocation.MyCommand.Name) - '$Computer' passed port test on port '$Protocol<code>:$Portx'"
                $Output.Result = $true
                $TcpClient.Close()
                $TcpClient.Dispose()
            }
            [pscustomobject]$Output
        }
    }
}

4. After saving the Test-Port.ps1 script, run the below command to test ports 22, 80, 443, and 53.

The -ComputerName parameter accepts the list of hostnames, FQDN, or IP addresses of the target machine(s).

The -Port parameter accepts an array of one or more port numbers to test.

./Test-Port.ps1 -ComputerName localhost -Port 22,80,443

As you can see below, the result shows that ports 22 and 80 are open (True), while port 443 is not (False).

Checking for open ports using PowerShell scripting
Checking for open ports using PowerShell scripting

To run the same script against multiple target endpoints and ports, edit the below code to add all target computers in the ComputerName parameter and port numbers in the Port parameter.

./Test-Port.ps1 `
    -ComputerName adamtheautomator.com,localhost,8.8.8.8 `
    -Port 22,80,443,53
Checking for open ports on multiple targets using PowerShell scripting
Checking for open ports on multiple targets using PowerShell scripting

Conclusion

In this article, you have learned how to check if a port is open or not in Linux. You have also learned to check if a port is open from a shell script and PowerShell. Now, you can use any of these methods to check if a port is open on your machine or any remote machine.

Don’t stop here, though. Check out other troubleshooting articles to continue honing your system administrator skills!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!