Skip to content

Linux Foundations / Follow traffic and find the fault ยท Step 43 of 46

Lesson: netstatSwitch
โ† Linux Foundations

Network operations

netstat

List listening ports and connections with netstat and its modern replacement, ss.

When a service "is running" but nobody can reach it, you need to know what is actually listening. netstat shows connections, listening ports, routing tables and interface counters.

netstat and ss

netstat belongs to the older net-tools package, which many Linux distributions no longer install by default. Its usual replacement is ss, from the iproute2 package. Learn both: you will find netstat on older systems and in old instructions, and ss on current ones. Windows and macOS also have a netstat, but their options differ from the Linux ones shown here.

Listening ports

bash
sudo netstat -tulpn
Proto Recv-Q Send-Q Local Address      Foreign Address    State    PID/Program name
tcp        0      0 0.0.0.0:22         0.0.0.0:*          LISTEN   812/sshd
tcp        0      0 127.0.0.1:5432     0.0.0.0:*          LISTEN   901/postgres
udp        0      0 0.0.0.0:68         0.0.0.0:*                   640/dhclient

The letters mean:

  • -t TCP and -u UDP
  • -l only listening sockets
  • -p show the process
  • -n show numbers instead of names

Root is needed to see process details for other users' sockets. UDP has no connections in the TCP sense, so the State column is usually empty.

The same idea with ss:

bash
sudo ss -tulpn

Its columns are arranged differently and the process appears as users:(("sshd",pid=812,fd=3)).

The local address matters

  • 0.0.0.0:22 accepts connections on every IPv4 address of the machine.
  • 127.0.0.1:5432 accepts connections only from the machine itself.
  • [::]:80 or :::80 is the IPv6 "all addresses" form.

A database bound to 127.0.0.1 cannot be reached from another computer, however open the firewall is.

Connections and other views

Leave out -l to see established connections:

bash
ss -tn
State  Recv-Q  Send-Q  Local Address:Port   Peer Address:Port
ESTAB  0       0       192.0.2.10:22        198.51.100.7:51514

Use -a to show both listening and non-listening sockets. netstat -r prints the routing table and netstat -i shows interface statistics. With iproute2, use ip route and ip -s link for those.

Try it

Run ss -tln and pick two lines. For each, decide whether another machine could reach it. Then start python3 -m http.server 8000 --bind 127.0.0.1 in one terminal, run ss -tlnp in another, and find it. Stop the server with Ctrl+C. The networking and SSH lab gives you a live shell to practise in.

Check your understanding

netstat

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.