netstat - Linux


Overview

netstat (network statistics) is a powerful command-line tool used for examining network connections, routing tables, interface statistics, masquerade connections, multicast memberships, and more. It allows administrators to monitor and troubleshoot network-related issues and performance. The tool is essential in both local and server environments for quick diagnostics and system insights.

Syntax

The basic syntax for netstat is as follows:

netstat [options]

Options/Flags

Here are the key options/flags for netstat:

  • -a: Show both listening and non-listening sockets.
  • -t: Display TCP connections.
  • -u: Display UDP connections.
  • -n: Show numerical addresses instead of trying to determine symbolic host, port, or user names.
  • -l: Show only listening sockets.
  • -p: Show the PID and name of the program to which each socket belongs.
  • -r: Display the routing table.
  • -i: Display a table of all network interfaces.
  • -s: Show statistics for all ports.

Each of these options can be combined to tailor output for specific needs. The default behavior without any options is to display all open connections and listening ports.

Examples

  1. Basic Usage: Display all active connections:
    netstat -a
    
  2. Filter for TCP Connections: Display only TCP connections:
    netstat -at
    
  3. Show Routing Table: View the system routing table:
    netstat -r
    
  4. Network Interfaces: View statistics for all network interfaces:
    netstat -i
    
  5. Verbose Output: Show detailed information, including non-standard ports:
    netstat -av
    

Common Issues

  • Permission Denied: Running netstat -p without sufficient privileges won’t display PID/user information. Use sudo:
    sudo netstat -p
    
  • Overwhelming Output: The output might be too verbose. Use tools like grep for filtering:
    netstat -at | grep ESTABLISHED
    

Integration

Combine netstat with other tools to perform advanced network monitoring:

  • Watch netstat Output in Real-Time:
    watch netstat -ta
    
  • Combine with grep:
    netstat -at | grep http
    
  • ss: A utility to investigate sockets.
  • ip: show / manipulate routing, devices, policy routing and tunnels.
  • lsof: list open files (can show files used by network).

For further reading, check the official net-tools page and Linux man pages for more detail on specific options and additional samples.