---
title: "All the Ways to Check If a Port is Open in Linux"
description: "Learn all the ways to check if a port is open in Linux and when you would use the various methods and techniques!"
canonical: "https://adamtheautomator.com/check-if-a-port-is-open-in-linux/"
---

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

> Learn all the ways to check if a port is open in Linux and when you would use the various methods and techniques!

Source: https://adamtheautomator.com/check-if-a-port-is-open-in-linux/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![All the Ways to Check If a Port is Open in Linux](https://adamtheautomator.com/wp-content/uploads/2022/08/All-the-Ways-to-Check-If-a-Port-is-Open-in-Linux.jpg)

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

[![](https://secure.gravatar.com/avatar/2788bb1a3f735603f81eca51d68daec56a9d97e805a10268fb2c20afcc76b81b?s=192&d=mm&r=g)Nicholas Xuan Nguyen](https://adamtheautomator.com/author/nicholas-xuan-nguyen/)10 August 20228 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Linux](/tag/linux/)[Networking](/tag/networking/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Check If a Port is Open in Linux Using netstat](#check-if-a-port-is-open-in-linux-using-netstat)
*   [Checking If a Port is Open Using ss](#checking-if-a-port-is-open-using-ss)
*   [Checking If a Port is Open Using lsof](#checking-if-a-port-is-open-using-lsof)
*   [Checking If a Port is Open Using nmap](#checking-if-a-port-is-open-using-nmap)
*   [Testing if a Port is Open from a Shell Script](#testing-if-a-port-is-open-from-a-shell-script)
*   [Testing If a Port is Open Using PowerShell](#testing-if-a-port-is-open-using-powershell)
*   [Conclusion](#conclusion)

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.

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   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,

Related:[A Windows Guy in a Linux World: Setting up SSH Command](https://adamtheautomator.com/ssh-command-in-linux/)

*   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.

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

Related:[Learning Ubuntu Apt Get Through Examples](https://adamtheautomator.com/ubuntu-apt-get/)

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`.

```bash
netstat -tulpn | grep LISTEN | grep :80
```

Related:[How to Search via Grep with Regex](https://adamtheautomator.com/grep-with-regex/)

> _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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-51.png)

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.

```bash
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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-52.png)

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.

```bash
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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-53.png)

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.

```powershell
apt install nmap -y
```

Related:[Effective Linux Port Scans for the Network Admin](https://adamtheautomator.com/linux-port-scan/)

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.

```bash
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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-54.png)

Checking If a Port is Open Using nmap

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

```bash
ssh user_name@159.89.176.25 -p 22
```

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

![SSHing into your server](https://adamtheautomator.com/wp-content/uploads/2022/08/image-55.png)

SSHing into your server

Related:[Leverage SSH and PowerShell to Securely Transfer Files Now](https://adamtheautomator.com/powershell-ssh/)

## 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.

Related:[How To Use Netcat and Level-Up Your Networking Skills!](https://adamtheautomator.com/how-to-use-netcat/)

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

```bash
nano check_port.sh
```

Related:[How to Edit Files with a Real PowerShell Text Editor](https://adamtheautomator.com/powershell-text-editor/)

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.

Related:[Understanding Bash If Else and other Conditional Statements](https://adamtheautomator.com/bash-if-else/)

```bash
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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-56.png)

Creating the Shell script

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

```bash
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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-57.png)

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.

Related:[Highly Effective Automation with Ansible AWX](https://adamtheautomator.com/ansible-awx/)

## 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](https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=net-6.0) class.

> _If your Linux computer does not have PowerShell yet, install it by following the instructions in this Microsoft documentation: [Install PowerShell on Linux](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-linux?view=powershell-7.2)._

1\. Launch PowerShell by running the below command.

```powershell
pwsh
```

![Launching PowerShell](https://adamtheautomator.com/wp-content/uploads/2022/08/image-58.png)

Launching PowerShell

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

```powershell
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](https://adamtheautomator.com/powershell-test-port/)._

```powershell
<#
	.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.

```powershell
./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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-59.png)

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.

```powershell
./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](https://adamtheautomator.com/wp-content/uploads/2022/08/image-60.png)

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](https://aws.amazon.com/premiumsupport/knowledge-center/ec2-windows-unable-connect-port/) articles to continue honing your system administrator skills!

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fcheck-if-a-port-is-open-in-linux%2F&text=All%20the%20Ways%20to%20Check%20If%20a%20Port%20is%20Open%20in%20Linux)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fcheck-if-a-port-is-open-in-linux%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fcheck-if-a-port-is-open-in-linux%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/08/Discover-the-Many-Ways-to-Get-an-IP-Address-on-Linux.jpg)

### [Get an IP Address on Linux : Discover the Many Ways](/get-an-ip-address-on-linux/)

Discover the many ways and tools that are available to get an IP address in Linux and learn how to incorporate those tools into scripts!

![](https://adamtheautomator.com/wp-content/uploads/2022/07/How-to-Update-Ubuntu-IP-and-Hostname-via-Bash.jpg)

### [How to Update Ubuntu IP and Hostname via Bash](/change-linux-ip-hostname-bash-script/)

Discover and learn how to change a Linux IP and Hostname via a Bash script in this new tutorial by ATA Learning!

![](https://adamtheautomator.com/wp-content/uploads/2022/06/Practical-Ping-Command-Linux-Examples.jpg)

### [Practical Ping Command in Linux Examples](/ping-command-in-linux/)

Discover the many ways that practical ping commands on Linux can be practically used in this ATA Learning tutorial.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
