How to Use netstat Command in Linux: Syntax and Examples
Use the
netstat command in Linux to display network connections, routing tables, and interface statistics. Run netstat [options] to see active connections or use flags like -t for TCP, -u for UDP, and -l to list listening ports.Syntax
The basic syntax of the netstat command is:
netstat [options]- Runs netstat with specified options.-t- Show TCP connections.-u- Show UDP connections.-l- Show only listening sockets.-a- Show all connections and listening ports.-n- Show numerical addresses instead of resolving hostnames.-p- Show the process ID and program name using the socket.
bash
netstat [options] # Common options: netstat -t # Show TCP connections netstat -u # Show UDP connections netstat -l # Show listening ports netstat -a # Show all connections and listening ports netstat -n # Show numerical addresses netstat -p # Show process info
Example
This example shows how to list all listening TCP ports with process information using netstat. It helps you see which programs are waiting for network connections.
bash
netstat -tlnp
Output
Active Internet connections (only servers)
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 1234/sshd
tcp6 0 0 :::80 :::* LISTEN 5678/nginx
Common Pitfalls
One common mistake is running netstat without sudo when trying to see process info, which results in missing PID/Program name. Another is forgetting the -n option, causing slow output due to DNS lookups.
Also, netstat may not be installed by default on some modern Linux systems; use ss as a modern alternative.
bash
netstat -tulpn # May show no process info without sudo sudo netstat -tulpn # Shows process info correctly
Quick Reference
| Option | Description |
|---|---|
| -t | Show TCP connections |
| -u | Show UDP connections |
| -l | Show listening sockets |
| -a | Show all connections and listening ports |
| -n | Show numerical addresses |
| -p | Show process ID and program name |
| -r | Show routing table |
| -i | Show network interfaces |
Key Takeaways
Use
netstat with options like -t, -u, and -l to filter network info.Add
-p with sudo to see which processes use network ports.Use
-n to speed up output by avoiding DNS lookups.If
netstat is missing, consider using the modern ss command.Remember
netstat shows active connections, listening ports, and routing info.