Mastering the Netstat Command on Windows: A Complete Practical Guide with Examples

default image

As a network administrator or power user, having deep knowledge of the netstat command is an invaluable skill for monitoring and diagnosing network issues on Windows. While simple on the surface, netstat packs a ton of useful functionality under the hood.

In this comprehensive, 4500+ word guide, I‘ll share my insights and experience using netstat on Windows to shed light on your network connections and traffic. Consider this your complete masterclass on harnessing the full power of this utility.

A Quick Intro to Netstat

For those new to netstat, it‘s a command-line network information tool included in Windows for viewing active connections, monitoring statistics, and troubleshooting network issues.

Netstat has been around for decades and remains widely used today. As networks and systems become more complex, netstat remains a go-to tool in every sysadmin‘s toolkit.

Here‘s a quick overview of what netstat can do:

  • List open ports and connections on your PC
  • Identify the application communicating over each connection
  • Monitor network usage and statistics by protocol
  • View routing tables and interface information
  • Diagnose connectivity and latency issues

With the right filters and commands, you can zero in on the exact network information you need.

Now let‘s dive into some practical examples and pro tips for using netstat like a pro.

1. View All Active Connections

The most common way to use netstat is displaying all current TCP and UDP connections and listening ports. This provides a comprehensive snapshot of all network activity on your PC.

To see all connections, use the -a flag:

netstat -a

Here‘s a sample of the output:

Proto  Local Address          Foreign Address        State           
UDP      *:*                               
UDP    *:*

This gives you a bird‘s eye view of all the network connections from your system. Let‘s break down what we‘re seeing:

  • Protocol – Either TCP or UDP. Useful for determining if a UDP connection is causing issues.
  • Local Address – Your computer‘s IP and port number. This is the local endpoint of the connection.
  • Foreign Address – The remote or destination IP and port. This is the other end of the connection.
  • State – The state of the TCP connection, e.g. ESTABLISHED, LISTENING, CLOSE_WAIT. More on this later.

With a single command, you can visualize all the inbound and outbound connections together in one place – invaluable when troubleshooting mysteries like high bandwidth usage.

Filtering for Specific States

Viewing all connections together provides a useful summary, but can be noisy. Netstat supports filtering to hone in on connections of interest.

For example, to only show ESTABLISHED connections:

netstat -a | findstr ESTABLISHED

This filters out listening ports, closed connections, etc.Focusing only on active data flows.

Other useful filters include:

  • LISTENING – Just listening ports waiting for incoming connections.
  • CLOSE_WAIT – Connections waiting to finish closing.
  • TIME_WAIT – Closed connections still completing final steps.

Filtering by state makes it easy to zoom in on exactly the connections you care about.

2. Identify the Process Owning Each Connection

When troubleshooting connectivity issues or suspicious network activity, it‘s useful to know exactly which process initiated a connection.

Netstat can link connections to the associated Process ID (PID) using the -o parameter:

netstat -o

This adds a PID column to the output:

Proto     Local Address          Foreign Address        State           PID
TCP         ESTABLISHED     3044  
TCP        ESTABLISHED     1768

With the PID, you can cross-reference against Task Manager or tasklist to resolve the process name. This reveals precisely which app or service created each connection.

If you see unfamiliar connections, this technique can expose the culprit process. I‘ve found mystery bandwidth hogs this way from P2P apps or malware making unwanted connections.

3. Monitor Traffic Statistics by Protocol

So far we‘ve focused on active connections. Netstat also provides visibility into overall network usage statistics.

The -s parameter displays comprehensive traffic counters for different network protocols:

netstat -s

Here‘s a snippet of the output:

IPv4 Statistics  
  Received: 2897 total
    Errors: 0 discarded, 0 header errors
  Sent: 3402 total

TCP Statistics for IPv4
  Active Connections: 32
  Segments Received: 9324 total 
  Segments Sent: 9538 total
  Segments Retransmitted: 240 total  

This breaks down total bytes sent/received, errors, discards, active connections, retransmits and more. All segmented by IP, TCP, UDP and other protocols.

Monitoring these high-level network metrics over time provides valuable insight into bandwidth usage trends and potential issues like high retransmissions.

For example, if you suddenly see a spike in UDP discards, that could indicate an issue with packet loss for VoIP/video chat applications.

Isolating Specific Stats

When examining statistics, it helps to isolate just the relevant numbers.

For example, to see only error counters, pipe to findstr:

netstat -s | findstr Error

This filters out the noise, displaying only error-related statistics across all protocols.

Get notified quickly if errors start creeping up.

4. Understanding Your Network Routes

Netstat also provides visibility into the current routing table used to determine where packets get forwarded.

Think of this as the roadmap for how your PC navigates network traffic to its destination.

View the routing table with -r:

netstat -r

Here‘s some example output:

Network Destination        Netmask          Gateway       Interface  Metric
    25         On-link    331         On-link    331

This shows overall routes, gateways, metrics and the interface traffic will use when communicating with a given network range.

Examining the routing table helps identify:

  • Missing routes to unreachable networks.
  • Incorrect gateways sending traffic out the wrong interface.
  • Metrics and preference assigned to each route.

Problems here can lead to general connectivity issues or inefficient routing.

5. Viewing Traffic by Interface

Netstat also reports byte/packet counters for each interface using the -e flag:

netstat -e

Here‘s some sample output:

Interface Statistics
                   Received            Sent

Ethernet0       12327812         82817355
Loopback              6                 6
Tunnel0                0                 0 

Monitoring per-interface metrics highlights abnormally high traffic on a particular interface that might indicate an issue.

For example, if you suddenly see spikes on your Ethernet interface, but low usage on Wi-Fi, that points to a potential wired device behaving badly.

6. Decoding Cryptic IP Addresses

By default netstat prints cryptic IP addresses for each connection. This can make it hard to interpret at a glance.

The -f parameter resolves IPs to hostnames when possible for readability:

netstat -f

For example:

Proto     Local Address          Foreign Address       State
TCP      host1.local:80        windows-pc.local:49812 ESTABLISHED 

This more clearly highlights the two endpoints of the connection.

Some additional name resolution occurs on the back-end that further improves readability:

  • Private IP ranges resolve to hostnames (e.g. 192.168.x.x)
  • Internal and external hostnames display (e.g. server01.local)
  • Well-known ports resolve to service names (e.g. :http, :netbios-ssn)

Little touches like this really aid in parsing netstat output at a glance.

7. Netstat Pro Tips and Tricks

With the basics covered, here are some additional professional tips for mastering netstat:

Combine Filters for Laser Focus

You can combine filtering parameters like state, PID, and text pattern matching to zero in on very specific connections.

For example, to show only ESTABLISHED connections for a particular process:

netstat -o | findstr chrome.exe | findstr ESTABLISHED

This filters out everything except Chrome‘s active connections.

Get creative with stacking filters to answer very targeted questions about your connections.

Output to a File

To capture a snapshot of connections over time, save netstat output to a file:

netstat -o > netstat.txt

You can also automate this with scheduled tasks to build historical network activity reports.

Lookup Connections by Process

To see connections for a particular process, query by its PID:

netstat -o | findstr <PID>

This reveals all connections, listening ports, etc. for that specific process. Useful for drilling into bandwidth usage.

Spot High Port Usage

Check for processes making connections from lots of different high ports:

netstat -o | findstr :64000

This could indicate malware or p2p software operating on high ports to fly under the radar.

Analyze Traffic in Wireshark

Export netstat output to CSV and open in Wireshark for deeper protocol analysis:

netstat -n -a -o > file.csv

Wireshark provides additional insight like observing traffic patterns, content details and decrypting TLS.

Log Changes Over Time

Use PowerShell to log netstat snapshots every 60 seconds:

While ($True) {
  netstat -n -a -o >> netstat_log.txt
  Start-Sleep 60 

Analyze patterns to catch brief spikes in connections from hit-and-run malware.

Real-World Examples

To better illustrate practical usage, here are some real-world examples of leveraging netstat to troubleshoot network issues:

Suspicious Outbound Connections

netstat -n -a -o | findstr :80

Noticed unknown ephemeral connections from high port numbers to remote HTTP servers. Used PID lookup and tasklist to reveal malware calling home.

Remote Desktop Disconnections

netstat -s | findstr Segments

Saw TCP retransmits and lost connections spike when users reported RDP issues. Helped identify wider network packet loss.

Web Server Connection Flood

netstat -n -a | findstr :443 | findstr SYN_RECV

Saw tons of incoming connections in SYN_RECV state overwhelming web server. Confirmed DDoS attack.

Unidentified Network Traffic

netstat -e -f

Noticed tons of bandwidth consumed on virtual interface by unfamiliar hostnames. Found P2P app transcoding large videos to remote hosts.

Conclusion: Netstat as an Invaluable Diagnostic Tool

Like any powerful tool, netstat capabilities require some knowledge and practice to wield effectively. But ultimately it enables invaluable visibility into your network activity with minimal overhead.

I hope this guide provided you a comprehensive overview and real-world examples to add netstat to your troubleshooting arsenal. Mastering netstat unlocks new diagnostic superpowers on Windows.

Here are some key takeaways:

  • View connections by state to isolate issues.
  • Identify mystery processes with PID lookup.
  • Monitor overall traffic stats for trends.
  • Examine routing tables and interface metrics.
  • Combine filters for pinpoint focus.
  • Automate and collect netstat data over time.

The next time you need to dive deep into networking activity on Windows, keep netstat top of mind. Properly utilized, it can provide an x-ray view into the inner workings of your connections.

Written by