Skip to main content

How to check for open TCP ports in Linux using netcat, ssh, nmap, telnet and even just cat

 


 

There are may ways to check for open TCP ports. Usually I prefer to use netcat or telnet, however in some cases (especially within docker containers) these tools are not installed or available. This post shows most common ways to check if a remote port is open or not.

telnet

Even though the telnet client tool is supposed to be used for the telnet protocol (ie. remotely logging in to a Unix computer before we had ssh), it is also a handy tool to check for an open port.

For example, we can use it to check if we can access www.google.com via HTTPS:

$ telnet www.google.com 443
Trying 142.250.70.196...
Connected to www.google.com.

If we see the "Connected" message, we can deduct from this that the port is open - even though there are protocol differences. Furthermore, if the service is unencrypted, telnet will show us status messages / protocol hints and versions etc. The following connects to a Google mail / SMTP server.

$ telnet smtp.google.com 25
Trying 74.125.24.27...
Connected to smtp.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP

Telnet used to be commonly installed on systems, however these days it's not always the case.

netcat

Netcat / nc can be used for many purposes including file transfers. It is also fairly easy to test for open ports.

$ nc -v google.com 443
Connection to google.com (142.250.70.174) 443 port [tcp/https] succeeded!

ssh 

You can also use the ssh client program to check for remote TCP ports. Just use the verbose option and look at the connection level output.

$ ssh -v -p 443 google.com

debug1: Connecting to google.com [142.250.70.174] port 443.
debug1: Connection established.

nmap

Nmap also offers quite a few different ways to scan for remote networks and ports - including full port and network scans which may be illegal if you don't own the target infrastructure.

However, checking a single port is easy

$ nmap -sT google.com -p 443
Starting Nmap 7.80 ( https://nmap.org ) at 2022-05-22 16:49 AEST
Nmap scan report for google.com (142.250.70.174)
Host is up (0.020s latency).
Other addresses for google.com (not scanned): 2404:6800:4015:801::200e
rDNS record for 142.250.70.174: mel04s02-in-f14.1e100.net

PORT    STATE SERVICE
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 0.10 seconds

bash

If none of the tools above are available, you can also just simply use the Linux Kernel to connect to a remote port for you like this.

if timeout 10 bash -c '</dev/tcp/google.com/443 &>/dev/null'
then
  echo "Google on TLS port 443 is open"
else
  echo "Google on TLS port 443 is closed"
fi

Comments