CommandsLinux

Netstat Command in Linux with Examples

Netstat Command on Linux

The netstat command stands as one of the most powerful network administration tools available in Linux systems. Whether you’re troubleshooting connectivity issues, monitoring network performance, or auditing your system for security vulnerabilities, netstat provides comprehensive insights into your system’s network connections, routing tables, interface statistics, and more. This article explores the full capabilities of the netstat command through practical examples, clear explanations, and advanced techniques to help you master this essential Linux networking tool.

Introduction to the Netstat Command

Netstat (network statistics) is a command-line utility that displays network connections, routing tables, interface statistics, protocol statistics, and other network-related information. System administrators and network troubleshooters rely on netstat to monitor network communications and diagnose problems across Linux environments.

The tool provides visibility into both incoming and outgoing network traffic, helping identify which applications are communicating over the network, which ports are open and listening, and which connections are active. This level of insight is invaluable for network management, security monitoring, and performance optimization.

Netstat serves multiple purposes in a Linux environment:

  • Identifying active connections and their states
  • Monitoring open ports and listening services
  • Analyzing network traffic patterns
  • Troubleshooting connectivity issues
  • Detecting potential security threats
  • Monitoring network interface performance

Understanding and effectively using netstat can significantly enhance your ability to manage and secure your Linux systems’ network operations.

Installing Netstat on Different Linux Distributions

Before you can use netstat, you need to ensure it’s installed on your system. On modern Linux distributions, netstat is part of the net-tools package, which may not be installed by default as newer alternatives like ss have emerged.

For Ubuntu/Debian-based systems:

sudo apt update
sudo apt install net-tools

For RHEL/CentOS/Fedora systems:

sudo yum install net-tools

or with newer versions:

sudo dnf install net-tools

For Arch Linux:

sudo pacman -S net-tools

For openSUSE:

sudo zypper install net-tools

Once installed, verify netstat is working by running a simple command:

netstat --version

If you see version information rather than a “command not found” error, you’ve successfully installed netstat and can begin using it.

Understanding Netstat Command Syntax and Output

The basic syntax of the netstat command follows this pattern:

netstat [options]

When run without any options, netstat displays a list of active internet connections. The default output is organized into columns that provide specific information about each connection:

Proto: The protocol used for the connection (TCP, UDP, etc.)

Recv-Q: The number of bytes queued on this connection waiting to be received and processed by the local application

Send-Q: The number of bytes queued that have not yet been acknowledged by the remote host

Local Address: The IP address and port number of the local end of the connection

Foreign Address: The IP address and port number of the remote end of the connection

State: The current state of the connection (ESTABLISHED, LISTENING, CLOSED, etc.)

For Unix domain sockets, netstat displays different information:

Proto: Always shows as “unix” for Unix domain sockets

RefCnt: Reference count (number of processes attached to this socket)

Flags: Various flags associated with the socket

Type: Socket type (STREAM, DGRAM, etc.)

State: Current state of the socket

I-Node: Inode number associated with the socket

Path: Path to the socket in the file system

Understanding these output columns is crucial for interpreting netstat results and diagnosing network issues effectively.

Essential Netstat Command Options

Netstat’s power comes from its versatile options that allow you to filter and customize the output to focus on specific aspects of your network. Here are the most essential options you’ll need:

-a (–all): Shows both listening and non-listening sockets

-t (–tcp): Displays TCP connections only

-u (–udp): Shows UDP connections only

-l (–listening): Shows only listening sockets

-p (–program): Displays the PID and name of the program to which each socket belongs

-n (–numeric): Shows numerical addresses instead of resolving host and port names

-r (–route): Displays the routing table

-i (–interfaces): Shows network interface statistics

-s (–statistics): Displays summary statistics for each protocol

-c (–continuous): Continuously displays information, refreshing every second

-v (–verbose): Provides more detailed output

These options can be combined to create powerful commands that provide precisely the information you need. For example, -atpn would show all TCP connections with program names and numerical addresses.

Displaying All Network Connections

To get a comprehensive view of all network connections on your system, both active and listening, use the -a option:

netstat -a

This command displays all connections regardless of their state or protocol, including both TCP and UDP connections as well as Unix domain sockets. The output provides a complete picture of your system’s network activity, showing established connections alongside servers that are open or listening.

For a more focused view that includes only Internet connections (excluding Unix domain sockets), combine with the relevant protocol options:

netstat -at   # All TCP connections
netstat -au   # All UDP connections

When troubleshooting network issues, it’s often helpful to include the process information and numerical addresses:

netstat -anp

This command requires root privileges to show process information for all connections. The output helps you identify which applications are communicating over the network and might be causing issues.

Filtering Connections by Protocol (TCP/UDP)

When diagnosing protocol-specific issues, it’s useful to filter connections by protocol type. Netstat makes this easy with dedicated options.

For TCP connections only:

netstat -t

This command lists all TCP connections on your system, including both established and listening connections. It’s particularly useful when troubleshooting web servers, email services, SSH connections, and other TCP-based applications.

For UDP connections only:

netstat -u

This displays all UDP connections, which are commonly used by DNS services, streaming media, VoIP applications, and certain types of game servers.

You can combine these protocol filters with other options to refine your view further:

netstat -tn   # TCP connections with numeric addresses
netstat -tup  # TCP and UDP connections with process information
netstat -atun # All TCP and UDP connections with numeric addresses

Understanding protocol-specific connections helps identify patterns and isolate issues related to particular services or applications.

Focusing on Listening Ports

Monitoring listening ports is crucial for security auditing and service management. To display only the ports that are open and listening for incoming connections, use the -l option:

netstat -l

This command shows all listening sockets across all protocols. To narrow down to specific protocols, combine with the protocol options:

netstat -lt   # Listening TCP ports
netstat -lu   # Listening UDP ports
netstat -lx   # Listening UNIX domain sockets

For a security-focused view that includes numeric addresses and process information:

netstat -lnp

This output is invaluable for security audits as it reveals which services are accepting connections and which processes are responsible for each listening port. Unexpected open ports might indicate security vulnerabilities or unauthorized services running on your system.

Regular monitoring of listening ports helps maintain a secure network configuration and detect changes that might compromise your system’s security.

Displaying Process Information with Network Connections

Identifying which processes are using network connections is essential for troubleshooting and security analysis. The -p option displays the PID (Process ID) and name of the program associated with each connection:

netstat -p

This command requires root privileges to show process information for all connections. Without root access, you’ll only see process information for connections owned by your user.

For a more practical approach, combine with other options:

netstat -tp   # Process information for TCP connections
netstat -lnp  # Process information for listening ports with numeric addresses

A particularly useful command for identifying which application is using a specific port is:

netstat -tulpn | grep <port_number>

This combination filters the output to show only the process using the specified port number. For example, to find which process is using port 80:

netstat -tulpn | grep ':80'

This technique is invaluable when troubleshooting port conflicts or identifying unexpected network activity on your system.

Numerical Output and Name Resolution

By default, netstat attempts to resolve IP addresses to hostnames and port numbers to service names, which can slow down the command execution. For faster results and to avoid potential DNS issues, use the -n option to display numerical addresses:

netstat -n

This command displays IP addresses instead of hostnames and port numbers instead of service names. The numerical output is not only faster but also more precise when troubleshooting network issues.

Netstat also offers options to selectively disable name resolution:

netstat --numeric-hosts   # Display numeric host addresses
netstat --numeric-ports   # Display numeric port numbers
netstat --numeric-users   # Display numeric user IDs

These selective options are useful when you want certain elements resolved while keeping others numeric, balancing readability with performance.

When working with firewall rules or configuration files that use numerical addresses, the numeric output from netstat provides consistency and clarity, making it easier to match connections with your configuration.

Monitoring Network Traffic in Real-Time

For continuous monitoring of network activity, netstat offers the -c option, which updates the display at regular intervals:

netstat -c

This command refreshes the output every second, providing a real-time view of network connections as they change. This continuous display is particularly useful for:

  • Monitoring connection attempts during troubleshooting
  • Observing connection patterns during peak usage periods
  • Detecting short-lived connections that might be missed in static output
  • Identifying intermittent network issues

Combine with other options for focused real-time monitoring:

netstat -ct    # Monitor TCP connections continuously
netstat -can   # Monitor all connections with numeric addresses continuously
netstat -ic    # Monitor interface statistics continuously

The last example is especially useful for tracking interface performance metrics in real-time, helping identify bandwidth issues or hardware problems as they occur.

Real-time monitoring with netstat provides immediate feedback on network changes, making it an essential technique for active troubleshooting sessions.

Examining Routing Tables

The routing table determines how packets are forwarded through your network. To display the kernel routing table, use the -r option:

netstat -r

This command shows destinations, gateways, and interfaces that define how traffic is routed from your system. The output includes:

  • Destination: Network or host to which packets are being sent
  • Gateway: Next hop address for the destination
  • Genmask: Network mask for the destination
  • Flags: Route status flags (U=up, G=gateway, H=host, etc.)
  • MSS: Default maximum segment size for TCP connections
  • Window: Default window size for TCP connections
  • irtt: Initial round trip time
  • Iface: Interface to use for sending packets to this destination

For a cleaner view with numerical addresses:

netstat -rn

This avoids hostname resolution, providing a faster and more direct view of the routing information.

Understanding your routing table is crucial for diagnosing connectivity problems, especially in complex networks with multiple gateways or when using VPNs. Incorrect routes can cause traffic to follow unintended paths or fail to reach destinations altogether.

Network Interface Statistics

To monitor the performance of your network interfaces, use the -i option:

netstat -i

This command displays statistics for each network interface, including:

  • MTU: Maximum Transmission Unit size
  • RX-OK/TX-OK: Successfully received/transmitted packets
  • RX-ERR/TX-ERR: Receive/transmit errors
  • RX-DRP/TX-DRP: Dropped packets on receive/transmit
  • RX-OVR/TX-OVR: Overruns on receive/transmit

For more detailed statistics, add the -e (extended) option:

netstat -ie

This provides additional information similar to what you would see with the ifconfig command.

To monitor these statistics over time, combine with the continuous option:

netstat -ic

This updates interface statistics every second, helping you track performance trends and identify potential hardware or driver issues. Consistently high error or drop counts often indicate hardware problems, misconfiguration, or capacity limitations that need attention.

Protocol Statistics and Performance

Netstat can provide detailed statistics for each network protocol with the -s option:

netstat -s

This comprehensive output shows counters for various events handled by each protocol, including packets received and sent, errors, connection attempts, and more. The statistics are grouped by protocol (IP, ICMP, TCP, UDP, etc.).

For protocol-specific statistics:

netstat -st   # TCP statistics only
netstat -su   # UDP statistics only

These focused views help when troubleshooting issues related to specific protocols. For example, high TCP retransmission counts might indicate network congestion or packet loss, while ICMP errors could point to routing problems or firewall issues.

Monitoring protocol statistics over time establishes baseline performance metrics for your system. Deviations from these baselines can alert you to potential problems before they affect users or services.

Advanced Filtering Techniques

While netstat’s built-in options provide powerful filtering capabilities, combining with other Linux tools like grep creates even more targeted outputs.

Find connections to a specific port:

netstat -an | grep ':80'

This filters the netstat output to show only connections to port 80, typically used for HTTP traffic.

Find connections in a specific state:

netstat -ant | grep 'ESTABLISHED'

This shows only established TCP connections, filtering out listening ports and connections in other states.

Find connections from a specific IP address:

netstat -an | grep '192.168.1.100'

This filters connections involving a particular IP address, useful when tracking activity from specific hosts.

Find which process is using a specific port:

sudo netstat -tulpn | grep ':22'

This identifies the process listening on port 22 (typically SSH), showing both the process ID and name.

These filtering techniques can be combined to create highly specific views of your network activity, tailored to particular troubleshooting scenarios or monitoring needs.

Practical Troubleshooting Examples

Let’s explore some real-world troubleshooting scenarios and how netstat can help resolve them.

Example 1: Identifying which application is using a port

If you’re trying to start a web server but get an “address already in use” error for port 80:

sudo netstat -tulpn | grep ':80'

This command reveals which process is already using port 80, allowing you to decide whether to stop that process or configure your web server to use a different port.

Example 2: Detecting unauthorized network connections

To check for unexpected outbound connections that might indicate malware:

netstat -anp | grep ESTABLISHED | grep -v 'localhost'

This shows all established connections to non-local addresses along with their associated processes, helping identify suspicious activity.

Example 3: Diagnosing network performance issues

If users report slow network performance:

netstat -i

Check for high error or drop counts on interfaces that might indicate hardware issues.

netstat -s | grep retransmit

Look for excessive TCP retransmissions that could indicate network congestion or packet loss.

Example 4: Troubleshooting connection failures

If applications can’t connect to a service that should be running:

netstat -lnp | grep '<service_port>'

Verify the service is actually listening on the expected port and interface.

These practical examples demonstrate how netstat’s versatility makes it an essential tool for a wide range of network troubleshooting scenarios.

Netstat Alternatives in Modern Linux

While netstat remains widely used, modern Linux distributions increasingly favor newer tools with enhanced capabilities. The primary alternative is the ss command, which provides similar functionality with improved performance:

ss -tuln   # Equivalent to netstat -tuln

The ss command is part of the iproute2 package and offers several advantages:

  • Faster execution, especially on systems with many connections
  • More detailed socket information
  • Better support for newer network features
  • Improved filtering capabilities

Other complementary network diagnostic tools include:

  • lsof: Lists open files, including network sockets (lsof -i :80)
  • ip: Manages routing, devices, and tunnels (ip route, ip addr)
  • nmap: Scans ports and discovers services (nmap localhost)
  • tcpdump: Captures and analyzes network packets
  • iftop: Displays bandwidth usage by connection

While learning these alternatives is valuable, netstat remains relevant for its ubiquity and compatibility across Linux distributions. Many system administrators still prefer netstat for its familiar syntax and output format, particularly in scripts and automated tasks.

Netstat Command Cheat Sheet

Here’s a quick reference guide for the most useful netstat commands:

Command Description
netstat -a List all connections and listening ports
netstat -at List all TCP connections
netstat -au List all UDP connections
netstat -l List only listening ports
netstat -lt List TCP listening ports
netstat -lu List UDP listening ports
netstat -lx List Unix socket listening ports
netstat -s Show statistics for all protocols
netstat -st Show TCP statistics
netstat -su Show UDP statistics
netstat -i Show network interface statistics
netstat -r Show routing table
netstat -p Show connections with PID/program name
netstat -n Show numerical addresses
netstat -c Continuous listing (updates every second)
netstat -an | grep :22 Find connections on port 22
netstat -tulpn Show listening ports with program and PID
netstat -ie Extended interface information (like ifconfig)

This cheat sheet covers the most common netstat usage scenarios and can serve as a quick reminder during troubleshooting sessions.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button