- How to check if a certain port is open and unused?
- 9 Answers 9
- Eg 1:
- Eg 2:
- All the Ways to Check If a Port is Open in Linux
- Prerequisites
- 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 lsof
- Checking If a Port is Open Using nmap
- Testing if a Port is Open from a Shell Script
- Testing If a Port is Open Using PowerShell
- Conclusion
How to check if a certain port is open and unused?
Could you please help and tell how can i find out if port 80 is open and unused so that I can start installation.
For what it’s worth, /etc/services is completely static. Grepping it can tell you if a port is officially designated by IANA or some such, but does not tell whether or not it’s in local use.
9 Answers 9
sudo netstat -anp | grep ':80 '
That should give you pid & name of the process that holds port 80
This can be achieved using the nc command as follows:
It will return TRUE if the port is already in use, or FALSE is it (i.e, available not listening currently).
I don’t recommend lsof or netstat method as it first try to scan all running PIDs to get all bounded ports:
# time lsof -i:8888 real 0m1.194s user 0m0.137s sys 0m1.056s``` # time nc -z 127.0.0.1 8888 real 0m0.014s user 0m0.011s sys 0m0.004s
Here 8888 is an unused port. The nc command is ~85 times faster in the above example.
Eg 1:
$ nc -z 127.0.0.1 80 && echo "IN USE" || echo "FREE" IN USE $ nc -z 127.0.0.1 81 && echo "IN USE" || echo "FREE" FREE
Eg 2:
If you are trying with a remote IP, it is better to add a timeout to auto-exit if it is not accepting connection for the specified time.
Its Google’s IP which is not used, so it will timeout after trying for 2 seconds.
This also works greatly when running inside the Docker image that uses host network. Inside the image, lsof incorrectly reports the port is not in use when it actually is.
The traditional version of nc does not include the -z option. See the differences between traditional and openbsd.
netstat -tln | tail -n +3 | awk '< print $4 >'
This one displays bind addresses of TCP listening endpoints. All other endpoints are free; Also if on Unix and you are not root, then you can’t bind to a ‘privileged’ port number (port number lower than 1024).
Explained in more details:
- netstat -tln — all listening tcp ports
- tail -n +3 — cut off the header of netstat command
- awk ‘< print $4 >‘ — print the fourth column that consists of [ip]:[port]
For the general case you still need to care to cut out all irrelevant interfaces; a listening address 0.0.0.0 is listening on all network cards, if there is an IP address then that’s the specific IP of the network card/network interface.
All the Ways to Check If a Port is Open in Linux
Ransomware recovery test drive: This technical workshop is designed to take you behind the scenes and shows you how to adopt strategies to automate recovery, ensuring you’re ready to become a recovery hero. REQUEST YOUR LAB
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.
- 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,
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 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 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 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.
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.
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).
The result confirms that users can SSH into the computer using the IP address and port.
The screenshot below shows a successful SSH connection to the server, proving that port 22 is open.
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.
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.
3. Run the shell script to start checking for the open ports you specified inside the script.
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.
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.
2. Next, create a file called Test-Port.ps1 using your text editor. This example uses nano.
3. Next, copy the below code into your editor. Save the file and exit the editor afterward.
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:$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
:$Portx'" $Output.Result = $false > else < $TcpClient.EndConnect($Connect) $TcpClient.Close() Write-Verbose "$($MyInvocation.MyCommand.Name) - '$Computer' passed port test on port '$Protocol:$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).
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
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.