Comprehensive Guide to the Netstat Command
The netstat utility is a fundamental command-line tool used for network diagnostics and monitoring. It displays active network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
Key Command Options
The behavior of netstat can be modified using various flags to filter the output or display specific types of network data.
Display Modes
- -a, --all: Shows both listening and non-listening sockets. By default,
netstatonly displays established connections, hiding those in a listening state. - -l, --listening: Lists only sockets that are currently listening for incoming connections.
- -s, --statistics: Displays detailed statistics for each protocol, similar to SNMP output.
- -r, --route: Prints the kernel routing table.
- -i, --interfaces: Displays a table of all network interfaces.
Protocol Selection
- -t, --tcp: Restricts output to TCP sockets.
- -u, --udp: Restricts output to UDP sockets.
Name Resolution and Formatting
- -n, --numeric: Displays numerical addresses and port numbers instead of resolving them to hostnames or service names. This is often preferred for faster execution and clearer logs, as it prevents the tool from querying DNS servers.
- -p, --programs: Shows the Process ID (PID) and the name of the program that owns each socket. This option usually requires root privileges.
- -c, --continuous: Refreshes the output continuous every second, allowing for real-time monitoring.
Practical Usage Scenarios
Viewing All TCP Connections Numerically
One of the most common combinations involves listing all TCP connections with numerical addresses to bypass DNS lookup delays.
# Display all TCP connections with numerical addresses
$ netstat -ant
# Output structure example:
# Proto Recv-Q Send-Q Local Address Foreign Address State
# tcp 0 0 192.168.1.5:22 203.0.113.10:52413 ESTABLISHED
Identifying Processes Listening on Ports
To secure a system, administrators often need to know which services are listening for incoming connections and which processes control them.
# List listening TCP sockets with process IDs
$ sudo netstat -lntp
# Output structure example:
# Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
# tcp6 0 0 :::80 :::* LISTEN 1234/nginx: master
Monitoring Network Statistics
For a broad overview of network traffic per protocol, the statistics flag provides insights into packet counts, errors, and collisions.
$ netstat -s