Sub topic 15
Listing and testing ports from the command line
This chapter assumes you know what a port, a socket and an ephemeral port are, and that you can run commands in a Linux-style shell. You will learn to answer two questions. Which ports is this machine listening on? Can I reach a given port on another machine? Run these commands only on hosts you own or are authorized to test.
Two questions, two tools
Inspecting ports means looking from two places.
- Local view: the operating system knows which processes have sockets open. You ask it directly with
ss,lsofornetstat. - Remote view: you try to connect from another machine and watch what happens. You use
nc, a short script, or a scanner such asnmap.
The two views can disagree. A service can be listening locally while a firewall blocks it from outside. The disagreement itself usually tells you where the fault is.
Listing listening sockets with ss
ss (socket statistics) is the modern replacement for netstat on Linux. The most useful combination of flags is:
# List listening TCP and UDP sockets with numeric ports and owning processes
ss -tulnp| Flag | Meaning |
|---|---|
| `-t` | Show TCP sockets |
| `-u` | Show UDP sockets |
| `-l` | Show only listening sockets (for UDP, sockets bound to a port) |
| `-n` | Do not resolve port numbers to names or addresses to hostnames |
| `-p` | Show the owning process (needs root to see other users' processes) |
Typical output, trimmed:
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=612,fd=13))
tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=801,fd=3))
tcp LISTEN 0 511 127.0.0.1:8080 0.0.0.0:* users:(("python3",pid=2310,fd=4))
tcp LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=801,fd=4))Read the Local Address:Port column carefully, because the address half matters as much as the port.
0.0.0.0:22means sshd accepts connections on every IPv4 address of the host.[::]:22is the same for IPv6.127.0.0.1:8080means the Python process accepts connections only from the host itself. A remote client will never reach it, no matter what the firewall says.127.0.0.53%lo:53is a local DNS stub resolver. It listens on port 53 but only on the loopback interface.
The -n flag matters. Without it, ss shows ssh instead of 22 and http-alt instead of 8080. That looks friendlier but hides the numbers you actually need to compare with firewall rules.
Filtering
You can filter by port instead of reading the whole table:
# Who is using port 443?
ss -tlnp 'sport = :443'
# All established connections to a remote port 443 (outgoing HTTPS)
ss -tn 'dport = :443'On macOS, ss is not available. Use lsof -iTCP -sTCP:LISTEN -nP. On older Linux systems, netstat -tulnp gives similar output. On Windows, netstat -ano lists ports with process IDs, and Get-NetTCPConnection -State Listen does the same in PowerShell.
Testing a remote port with nc
nc (netcat) opens a connection and reports whether it worked:
# Test whether a TCP port on a host you own is reachable
nc -vz 192.0.2.10 22-v prints a verbose result and -z means "scan only": connect, then close without sending data. A success looks like Connection to 192.0.2.10 22 port [tcp/ssh] succeeded! on the common OpenBSD version. You can also test a range with nc -vz 192.0.2.10 20-25.
Add -w 3 to give up after three seconds. Without a timeout, a filtered port can make you wait a long time.
Reading the three outcomes
A TCP connection test ends in one of three ways. Each points to a different cause.
| Result | What happened on the wire | Usual meaning |
|---|---|---|
| Succeeded | The three-way handshake finished (SYN, SYN-ACK, ACK) | Something is listening and nothing blocked the path |
| Connection refused | The host answered with a TCP reset (RST) | The host is up, but no process listens on that port, or a firewall actively rejects |
| Timed out | No answer at all | A firewall silently drops the packets, the host is down, or the route is broken |
The distinction between "refused" and "timed out" is the single most useful clue in port troubleshooting. A refusal proves your packets reached the machine. A timeout proves nothing, except that no reply came back.
Scripting the same test in Python
When you need to test several ports and label the result, a short script is clearer than parsing nc output. This one uses only the standard library.
import socket
import sys
def probe(host, port, timeout=3.0):
try:
with socket.create_connection((host, port), timeout=timeout):
return "open"
except ConnectionRefusedError:
return "closed (connection refused)"
except TimeoutError:
return "filtered or host down (timed out)"
except OSError as exc:
return f"error: {exc}"
if __name__ == "__main__":
host = sys.argv[1]
for arg in sys.argv[2:]:
print(f"{host}:{arg}", probe(host, int(arg)))Save it as probe.py and run python3 probe.py 192.0.2.10 22 80 443. The except order matters. ConnectionRefusedError and TimeoutError are both subclasses of OSError, so they must come before the general OSError clause. On Python versions before 3.10, TimeoutError is not what socket.create_connection raises. Use socket.timeout there.
Testing UDP is different
TCP has a handshake, so a connection attempt gives a definite answer. UDP has no handshake. If you send a datagram to a UDP port, a closed port may return an ICMP "port unreachable" message, but an open port usually says nothing, and a firewall that drops packets also says nothing.
nc -vzu host 53 therefore reports "succeeded" in many cases where nothing is listening. The only reliable UDP test is to send a real request and look for a real reply. For DNS, use dig @192.0.2.10 example.com. For NTP, query with an NTP client. Use ss -ulnp on the server to confirm a process is bound.
Scanning with nmap
nmap tests many ports at once and classifies each as open, closed or filtered. Those states map onto the three outcomes above: a filtered port is one where probes get no answer.
# Scan the 1000 most common TCP ports on a host you own
nmap 192.0.2.10
# Scan specific ports and detect service versions
nmap -p 22,80,443 -sV 192.0.2.10Scanning hosts that are not yours can violate policy or law. Limit it to your own systems or ones where you hold written permission.
Common errors
- Testing from the wrong place. A test from the server to itself (
nc -vz localhost 8080) succeeds even when the firewall blocks outside traffic. Test from a second machine. - Ignoring the bind address. A service on
127.0.0.1is invisible to remote tests. Change its configuration to listen on0.0.0.0or a specific interface address, if it should be reachable. - Reading "succeeded" as "the right service". A successful connection shows only that something accepted it. The port number is a convention, not proof of the protocol, as a later chapter explains. Use
nc host 25or a similar check and read the banner when it matters. - Forgetting
sudowith-p. Without root,ss -pshows no process for sockets owned by other users, and the column looks empty. - Mixing IPv4 and IPv6. A service may listen on
[::]:80while your test targets an IPv4 address that the firewall handles differently. Test both when a name resolves to both.
Reading a banner
Many plain-text services announce themselves as soon as you connect. You can read that greeting with nc:
nc -w 3 192.0.2.10 22An SSH server replies with a line such as SSH-2.0-OpenSSH_9.6. This confirms the protocol far better than a bare "succeeded". Press Ctrl+C to leave if the connection stays open.
Exercise
From your laptop, nc -vz -w 3 192.0.2.10 8080 prints "Connection refused". On the server, ss -tlnp shows 127.0.0.1:8080 owned by a Python process. Is the firewall the cause? What would you change, and what result would you expect afterwards?
Show answer
The firewall is not the cause. A refusal means the host answered with a reset, so the packets arrived. The service is bound only to the loopback address 127.0.0.1, so it accepts connections only from the server itself. Reconfigure the service to listen on 0.0.0.0 (or the server's interface address) and restart it. ss -tlnp should then show 0.0.0.0:8080, and the laptop test should print "succeeded", unless a firewall then blocks port 8080, in which case it would time out.
Exercise
Why can nc -vzu 192.0.2.10 123 report success even if no NTP server runs on that host? How would you test it properly?
Show answer
UDP has no handshake, and a datagram that is silently dropped or ignored produces no error, so the tool cannot tell an open port from one that is filtered or unused. A reliable test sends a real NTP request and checks for a reply, for example with an NTP client such as ntpdate -q 192.0.2.10 or chronyc/ntpdig. On the server, ss -ulnp should show a process bound to UDP port 123.