Linux Netstat Command - How To Use Netstat For Linux Network Management

Posted on March 21, 2024

Netstat is a powerful command-line tool that provides valuable insights into your computer's network connections and performance. This article will explore what netstat does, how to use it on Linux systems, and ways to leverage netstat for network troubleshooting and monitoring.

Overview of the Netstat Command

What is Netstat?

Netstat, short for "network statistics", is a command-line tool that helps you understand and check your computer's network connections and performance. It gives you information about:
  • Active network connections: See what your computer is connecting to
  • Routing tables: View the paths your computer uses to send information
  • Network interfaces: Get details on your network devices and their activity

With netstat, you can get a clear picture of your network status and find any issues.

Basic Syntax

To use netstat, you type `netstat` followed by one or more options. The general format is:

netstat [options]

You can combine different options to get the specific information you need. Some common examples:

  • netstat -a: Shows all active connections
  • netstat -r: Displays the routing table
  • netstat -i: Lists network interface statistics

The options let you adjust netstat's output to focus on the details that matter for your troubleshooting or analysis.

Using Netstat on Linux

Netstat is available on most Linux distributions. Here are some useful netstat commands for Linux:

  • netstat -at: Shows all active TCP connections
  • netstat -au: Shows all active UDP connections
  • netstat -l: Lists all listening sockets
  • netstat -s: Displays summary statistics for each protocol
  • netstat -tp: Shows the PID and name of the program to which each socket belongs

For example, to see all active TCP connections, run:

netstat -at

This will output something like:

Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:mysql*               LISTEN     
tcp        0      0  *               LISTEN     
tcp        0      0 localhost:6379*               LISTEN

Each line shows a TCP socket, with details like:

  • Local and foreign addresses and ports
  • The socket's current state (e.g., LISTEN, ESTABLISHED)
  • Receive and send queue sizes

You can use grep to filter the output, like:

netstat -at | grep http

To only show sockets related to HTTP.

Troubleshooting with Netstat

Netstat is a powerful tool for finding network issues on Linux servers. Some common use cases:

  • Check for ports in use: netstat -tunlp shows which processes are using which ports
  • Monitor connections to a specific port: netstat -anp | grep :80 tracks connections to port 80
  • Find out which process is using a port: netstat -tulpn lists the PID for each listening port
  • Analyze failed connection attempts: Look for sockets in TIME_WAIT or CLOSE_WAIT states

By using netstat to examine your network connections, you can pinpoint problems like port conflicts, unresponsive services, or traffic overloads. It's an essential part of any Linux sysadmin's network troubleshooting toolkit.

Displaying Network Connection Information

Listing All Active Connections

One of the most common uses of `netstat` is to show all active network connections on your Linux system. To do this, run:

netstat -a

This command shows both listening and established connections, giving an overview of your network activity. The output includes details like the protocol (TCP or UDP), local and foreign addresses, and the current state of each connection.

For example:

Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:mysql*               LISTEN     
tcp        0      0       ESTABLISHED
udp        0      0*                          

Here, we can see a listening MySQL server, an established SSH connection, and a UDP connection for DHCP (bootpc).

Listing TCP and UDP Connections

If you want to focus on specific types of connections, `netstat` lets you filter for TCP or UDP. To list only active TCP connections, use:

netstat -at

And for UDP connections:

netstat -au

This is useful when you're troubleshooting issues related to a specific protocol or service. For instance, if you're having problems with a web server, you might use netstat -at to check its TCP connections.

Showing Listening Ports

Another helpful use of `netstat` is to show only listening ports. These are ports that are open and waiting for incoming connections. To list all listening ports, run:

netstat -l

You can also combine this with the -t or -u options to filter for TCP or UDP ports:

netstat -lt netstat -lu

This is a quick way to see which services are running on your system and which ports they're using. For example:

Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0  *               LISTEN     
tcp6       0      0 [::]:https              [::]:*                  LISTEN

Here, we can see that the system is running an HTTP server on port 80 (http) and an HTTPS server on port 443 (https), both listening for IPv4 and IPv6 connections.

By using these netstat commands to show active connections and listening ports, you can get a clear picture of your Linux system's network services and find any potential issues or security risks.

Monitoring Network Statistics

Showing Interface Statistics

The `netstat` command can also give useful statistics about your network interfaces. To show this information, use:
netstat -i

This command shows a list of all network interfaces on your system, along with important metrics for each one. The output includes:

  • Interface name (e.g., eth0, lo)
  • MTU (Maximum Transmission Unit) size
  • Number of packets received (RX) and sent (TX)
  • Number of receive (RX) and transmit (TX) errors
  • Number of received (RX) and sent (TX) packets dropped

For example:

Kernel Interface table
eth0   1500  1234      0      0 0         5678      0      0      0 BMRU
lo    65536   100      0      0 0          100      0      0      0 LRU

Here, we can see statistics for the eth0 (Ethernet) and lo (loopback) interfaces. The RX columns show the number of packets received, received with errors, dropped, and overruns. The TX columns show the same information for sent packets.

Monitoring these statistics can help you find performance issues or errors on specific interfaces. For instance, a high number of RX-ERR or TX-ERR might show a physical problem with a network cable or port.

Showing Kernel Routing Table

In addition to interface statistics, `netstat` can show your system's kernel routing table. This is a list of network routes that tell your system how to send packets to different network destinations. To see the routing table, use:
netstat -r

This command shows each route as a line with several fields:

  • Destination: The destination network or host
  • Gateway: The gateway (router) used to reach the destination
  • Genmask: The netmask for the destination network
  • Flags: Flags showing route features (e.g., U for up, G for gateway)
  • MSS: The default maximum segment size for TCP connections over this route
  • Window: The default TCP window size
  • irtt: The initial round trip time (irtt) for the route

For example:

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         UG        0 0          0 eth0   U         0 0          0 eth0

Here, we can see two routes. The first is the default route, which sends all traffic to the gateway at The second is a route for the local network, which is directly connected to the eth0 interface.

By looking at the routing table, you can understand how your system directs network traffic and troubleshoot connectivity issues. For instance, if packets aren't reaching a specific destination, you might check the routing table to see if there's a valid route for that destination.

netstat's interface statistics and routing table displays are powerful tools for monitoring your Linux system's network performance and connectivity. By keeping an eye on these metrics, you can find and fix network problems before they affect your users or applications.

Advanced Usage and Troubleshooting

Monitoring Network Activity Continuously

The `netstat` command can be used to monitor network activity in real-time continuously. By using the `-c` option, `netstat` will refresh its output at regular intervals, allowing you to see changes in network connections and statistics as they happen.

For example, running:

netstat -c

This command will show the network information and update it every second. This is useful for finding sudden changes in network behavior, such as a spike in connections or a sudden drop in throughput. By monitoring the output over time, you can find trends and anomalies that might indicate a developing problem.

Finding Processes Using Ports

When troubleshooting network issues, it's often helpful to know which processes are using which network ports. The `netstat` command's `-p` option shows the PID (Process ID) and name of the program linked with each socket.

For instance:

netstat -p

This command will show a list of active network connections, along with the PID and name of the program that owns each socket. If you see a port in use that you don't recognize, you can use the PID to investigate further with tools like ps and lsof.

This is especially useful for troubleshooting port conflicts. If two programs are trying to use the same port, netstat -p will show you which processes are involved. You can then take steps to reconfigure one of the programs to use a different port.

It's also a valuable security tool. By regularly checking for unfamiliar processes using network ports, you can find suspicious activity that might indicate a hacked or compromised system.

Combining Netstat with Grep

The output of `netstat` can be long, especially on systems with many network connections. To make it easier to find the information you need, you can use `grep` to filter `netstat`'s output.

For example, to show only connections to a specific port (e.g., 80 for HTTP), you can use:

netstat -an | grep ':80'

This pipes the output of netstat -an (which shows all sockets, numeric output) to grep, which searches for lines containing :80. The result is a list of all connections involving port 80.

You can use a similar method to find connections to a specific IP address:

netstat -an | grep ''

This is a powerful way to quickly find relevant information, especially when you're dealing with a busy system or a complex network issue. By combining netstat with grep, you can answer questions like:

  • Is my web server accepting connections on port 80?
  • Are there any connections to a suspicious IP address?
  • Which clients are currently connected to my database server?

With these advanced netstat techniques - continuous monitoring, finding processes, and filtering output - you can take your network troubleshooting skills to the next level. Whether you're a system administrator managing a fleet of Linux servers or a power user trying to optimize your own system, netstat is an important tool to have in your kit.

Understanding Network Sockets

Network sockets are the basic parts of network communication on Linux systems. A socket is an endpoint for sending and receiving data across a network. It's a combination of an IP address and a port number, which together identify a specific network service or connection.

When you run netstat, you see a list of all the active sockets on your system. Each line in the output shows a socket, with information about its protocol, local and remote addresses, and current state.

For example:

Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:6379*               LISTEN
tcp        0      0      ESTABLISHED

In this output, the first line shows a TCP socket that's listening on localhost ( port 6379. This is a typical setup for a Redis server. The second line shows an established SSH connection from port 54321 to port 22 (the default SSH port).

By looking at the sockets in netstat's output, you can understand your system's network communication patterns. You can see which services are running, which ports they're using, and who is connecting to them.

This information is valuable for fixing network issues. For instance, if you're having trouble connecting to a service, you can use netstat to check that the service is running and listening on the correct port. If you see many connections in an unusual state (like TIME_WAIT or CLOSE_WAIT), it might show a problem with a client or a server.

You can also use netstat to find security issues, like unknown services or suspicious connections. By regularly checking the list of active sockets, you can make sure that your system is only running the services you expect, and that it's not being accessed by unknown clients.

In summary, understanding network sockets is key to effectively using netstat and managing Linux network services. By knowing how to interpret netstat's output, you can find problems, improve performance, and keep your system secure.

Analyzing Network Traffic with Netstat

Showing Network Traffic Statistics

The `netstat` command is a useful tool for analyzing network traffic on your Linux system. One helpful option is `-s`, which shows detailed statistics about the network traffic handled by each protocol.

To view these statistics, run:

netstat -s

This command will print a summary of the traffic statistics for TCP, UDP, ICMP, and other protocols. The statistics include information like:

  • Segments sent and received
  • Segments retransmitted
  • Errors received
  • Packets sent and received
  • Packets dropped

For example, in the TCP section, you might see:

    1234 active connections openings
    5678 passive connection openings
    10 failed connection attempts
    123 connection resets received
    1 connections established
    1234567 segments received
    7654321 segments send out
    123 segments retransmited
    0 bad segments received.
    1234 resets sent

These statistics can help you find network performance issues. A high number of retransmitted segments might show network congestion or an unreliable network link. A large number of failed connection attempts could point to a problem with a service or a port scanner attack.

Similarly, the UDP and ICMP sections show statistics for those protocols. High levels of ICMP "destination unreachable" messages could mean routing problems or a DDoS attack.

By regularly checking these statistics, you can set a baseline for your system's normal network activity. Any large changes from this baseline can be an early warning sign of a developing problem.

Checking Network Bandwidth Usage

In addition to protocol statistics, `netstat` can show you how much network bandwidth each interface is using. The `-i` option shows a table of interface statistics, including the number of bytes and packets sent and received.

To see this information, run:

netstat -i

The output will look something like this:

Kernel Interface table
eth0   1500 1234567   0      0 0      7654321    0      0      0 BMRU
lo    65536   1234   0      0 0         1234    0      0      0 LRU

The RX-OK and TX-OK columns show the total number of bytes received and transmitted by each interface. By checking these numbers over time, you can see which interfaces are handling the most traffic and whether any are approaching their capacity limits.

For instance, if you see that an interface's TX-OK value is consistently high and growing, it might mean that the interface is saturated and could benefit from a bandwidth upgrade.

You can also use this information to find bandwidth hogs - applications or users that are using a large portion of your network resources. By matching high bandwidth usage with other system activity, you can find the source of the traffic and take steps to manage it.

netstat's traffic statistics and bandwidth monitoring features are important for any Linux system administrator or network manager. By watching these metrics, you can make sure that your network is performing well and that you have the capacity to handle your workload. With netstat in your toolbox, you're well-equipped to analyze and troubleshoot Linux network traffic.

Netstat and Linux Server Management

Monitoring Network Services on Linux Servers

Netstat is a useful tool for managing and securing Linux servers. One of the most helpful commands for server administrators is:

netstat -tulpn

This command lists all TCP and UDP ports that are being listened on, along with the related processes. The output looks like this:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0    *               LISTEN      1234/sshd       
tcp        0      0 *               LISTEN      5678/cupsd      
tcp6       0      0 :::80                   :::*                    LISTEN      9012/apache2

Each line shows a network service that is running on the server, along with:

  • The protocol (TCP or UDP)
  • The local address and port
  • The foreign address and port (if any)
  • The state of the socket (e.g., LISTEN, ESTABLISHED)
  • The PID and name of the process that owns the socket

By running this command regularly, you can track which network services are running on your server. You can check that all the needed services are up (like SSH, HTTP, and databases) and that there are no unexpected services listening.

This is also an important security practice. By monitoring the listening ports, you can find any unauthorized services that might have been installed by an attacker or a rogue application. If you see any unfamiliar services or ports, you can use the PID to investigate the related process.

In addition, you can use netstat to troubleshoot service issues. If a service isn't responding, you can check netstat to make sure it's running and listening on the correct port. If it's listening but not responding, you might need to check the service logs or restart the service.

Overall, running netstat -tulpn should be a regular part of your Linux server management routine. It's a quick and easy way to monitor your network services, catch potential issues, and keep your servers secure. Combined with other tools like ps, lsof, and log monitoring, netstat is a key part of a complete server management strategy.

Netstat as a Monitoring Tool

Using Netstat with Monitoring Systems

Netstat is useful for more than just interactive troubleshooting. It can also be integrated with monitoring systems for automatic network monitoring. By analyzing the output of netstat commands, you can send network connection and statistics data into tools like Nagios or Prometheus.

This lets you set up automatic checks and alerts for network problems. For example, you could create an alert that triggers when the number of established connections to a specific port goes above a limit, or when the number of UDP packets dropped by an interface increases.

By integrating netstat with your monitoring system, you can find and fix network issues before they impact users. Instead of manually running netstat when a problem is reported, your monitoring system can constantly check netstat metrics and alert you to possible issues.

This type of automatic monitoring is especially helpful for large or complex networks, where manual checking isn't practical. It's also useful for finding intermittent issues that might be missed by spot checks.

Scripting with Netstat for Automatic Monitoring

To fully use netstat for monitoring, it's often helpful to use scripts to automate the collection and processing of netstat data. Simple shell scripts can run netstat commands on a schedule, parse the output, and send the data into a monitoring system or log file.

For more complex processing, you might use a scripting language like Python to work with and analyze the netstat data. For example, a Python script could:

  1. Run netstat -i to get interface statistics
  2. Parse the output to extract the bytes sent and received for each interface
  3. Calculate the change in bytes over time to get bandwidth usage
  4. Check the bandwidth usage against defined limits
  5. Send an alert if any limits are exceeded

By scripting netstat, you can create custom monitoring solutions matched to your network's specific needs. You can define your own metrics, limits, and alert conditions, and have the script run on a schedule that works for your environment.

Scripting also enables more advanced data analysis. You could have a script that combines netstat data over time and generates reports on long-term network usage trends. Or you could compare netstat data with other system metrics to find the root causes of performance issues.

Whether you use simple shell scripts or more advanced Python programs, scripting is a powerful way to automate netstat monitoring and get more value from the netstat data.

In conclusion, netstat is not just a one-time troubleshooting tool but a valuable data source for ongoing network monitoring. By integrating netstat with monitoring systems and using scripts to automate data collection and analysis, you can actively manage your network's health and performance. With a little setup, netstat can be the heart of a strong network monitoring solution.

Netstat and Network Security

Identifying Suspicious Network Activity

Netstat is a useful tool for finding suspicious network activity on your Linux system. By using the command `netstat -anp`, you can show all active network connections along with the linked processes.

This output can help you find unusual or unauthorized connections that could mean a security breach or malware infection. Here's what to look for:

  • Unfamiliar local or foreign addresses: Connections to or from IP addresses that you don't know could be a sign of unauthorized access.
  • Unexpected ports: Connections on unusual ports, especially high-numbered ports, might indicate malware activity or a backdoor.
  • Unknown processes: Connections linked with unfamiliar processes could mean that an attacker has installed unauthorized software.

For example, if you see a connection like this:

tcp   0   0 ESTABLISHED 1234/sshd  

This shows an SSH connection from to your system ( on port 22. If you don't expect SSH access from that IP, it could be an unauthorized login attempt.

Similarly, a line like this:

tcp   0   0 ESTABLISHED 5678/mystery_process

This could be very suspicious. It shows an outgoing connection from your system to an unfamiliar IP on port 31337, which is often used by trojans and backdoors. The unfamiliar process name adds to the concern.

By regularly checking netstat -anp, you can find these kinds of red flags early. This allows you to investigate further with tools like lsof, ps, and log analysis to determine if there's a real security issue.

It's a good idea to run this check regularly and anytime you see signs of a possible breach, like high CPU usage or suspicious log entries. By using netstat to find and respond to security issues quickly, you can reduce the damage and keep your Linux system safe.

Key Takeaways

  • netstat -a shows all active network connections, giving a clear picture of your network status
  • Use options like -t, -u, and -l to filter for TCP, UDP, or listening ports
  • netstat -i displays valuable statistics about your network interfaces to find performance issues
  • Monitor network activity in real-time with netstat -c and find which processes are using ports with netstat -p
  • Analyze traffic with netstat -s to see detailed statistics for each protocol and catch potential problems