Netstat And Connection Monitoring
Category: Network Tools and Commands
Type: Network Tools & Commands
Generated on: 2025-07-10 09:14:18
For: Network Engineering, Administration & Technical Interviews
This cheatsheet provides a practical guide to using netstat and related connection monitoring tools for network administrators and engineers. It covers basic syntax, practical examples, advanced usage, and troubleshooting scenarios across different platforms.
1. Tool Overview
netstat(Network Statistics): Displays network connections (TCP, UDP, raw sockets), routing tables, interface statistics, and multicast memberships. Useful for identifying open ports, established connections, and network traffic. Note:netstatis being superseded byss(Socket Statistics) in many Linux distributions, asssprovides more detailed information and is faster. However,netstatremains widely used.ss(Socket Statistics): A modern replacement fornetstat, providing more comprehensive and faster socket information. Linux only.tcpdump(TCP Dumper): A powerful command-line packet analyzer. Captures and displays network traffic based on specified filters. Essential for debugging network issues and analyzing traffic patterns.lsof(List Open Files): While primarily used for listing open files, it can also be used to identify the process using a specific network port or connection.nc(Netcat): A versatile tool for reading from and writing to network connections using TCP or UDP. Useful for testing network connectivity, port scanning, and data transfer.nmap(Network Mapper): Primarily a security scanning tool, but also useful for discovering hosts and services on a network. Can identify open ports, operating systems, and running applications.
When to Use Which Tool:
netstat/ss: Quick overview of network connections and listening ports. Good for initial troubleshooting.tcpdump: Deep dive into network traffic. Used for capturing and analyzing packets to diagnose specific issues.lsof: Identify which process is using a specific port.nc: Test connectivity to a specific port or transfer data over a network.nmap: Discover hosts, services, and vulnerabilities on a network. Use responsibly and with proper authorization.
2. Basic Syntax
netstat [options]ss [options] [filter]tcpdump [options] [expression]lsof [options]nc [options] host portnmap [options] target
3. Practical Examples
-
netstat -an: List all active network connections and listening ports (TCP, UDP).Terminal window netstat -an# Sample Output (Linux)Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address Statetcp 0 0 0.0.0.0:22 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:631 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:3350 127.0.0.1:631 ESTABLISHEDtcp 0 0 127.0.0.1:631 127.0.0.1:3350 ESTABLISHEDudp 0 0 0.0.0.0:68 0.0.0.0:*udp 0 0 127.0.0.53:53 0.0.0.0:*Terminal window # Powershell (Windows - using Get-NetTCPConnection and Get-NetUDPListener)Get-NetTCPConnection | Format-Table -AutoSizeGet-NetUDPListener | Format-Table -AutoSize -
ss -lt: List all listening TCP ports.Terminal window ss -lt# Sample OutputState Recv-Q Send-Q Local Address:Port Peer Address:Port ProcessLISTEN 0 128 0.0.0.0:22 0.0.0.0:*LISTEN 0 128 127.0.0.1:631 0.0.0.0:* -
tcpdump -i eth0 port 80: Capture all traffic on interfaceeth0to or from port 80 (HTTP).Terminal window tcpdump -i eth0 port 80# Sample Output (showing captured packets)tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes10:00:00.123456 IP 192.168.1.100.50000 > 192.168.1.1.80: Flags [S], seq 1234567890, win 65535, options [mss 1460,nop,wscale 7,nop,nop,TS val 123456789,TS ecr 0,sackOK,eol], length 010:00:00.123500 IP 192.168.1.1.80 > 192.168.1.100.50000: Flags [S.], seq 4567890123, ack 1234567891, win 65535, options [mss 1460,sackOK,TS val 987654321,TS ecr 123456789,nop,wscale 7], length 0 -
lsof -i :80: List the process listening on port 80.Terminal window lsof -i :80# Sample OutputCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEnginx 1234 www-data 6u IPv4 123456789 0t0 TCP *:http (LISTEN)nginx 1235 www-data 6u IPv4 123456789 0t0 TCP *:http (LISTEN) -
nc -zv google.com 443: Test connectivity to Google’s HTTPS port.Terminal window nc -zv google.com 443# Sample OutputConnection to google.com 443 port [tcp/https] succeeded! -
nmap -p 80,443 192.168.1.1: Scan ports 80 and 443 on the host 192.168.1.1.Terminal window nmap -p 80,443 192.168.1.1# Sample OutputStarting Nmap 7.92 ( https://nmap.org ) at 2023-10-27 10:00 PDTNmap scan report for 192.168.1.1Host is up (0.00034s latency).PORT STATE SERVICE80/tcp open http443/tcp open httpsNmap done: 1 IP address (1 host up) scanned in 0.12 seconds
4. Common Options
netstat:-a: All connections and listening ports.-n: Numeric addresses (no DNS resolution). Faster and avoids potential DNS poisoning.-t: TCP connections.-u: UDP connections.-p: Display PID/Program name (requires root privileges).-l: Listening sockets only.-r: Routing table.-i: Interface statistics.
ss:-l: Listening sockets.-t: TCP sockets.-u: UDP sockets.-a: All sockets.-n: Numeric addresses.-p: Show process using socket.-o: Show timer information.-s: Summary statistics.
tcpdump:-i <interface>: Specify the interface to listen on (e.g.,eth0,wlan0). Usetcpdump -Dto list available interfaces.-n: Don’t resolve hostnames.-nn: Don’t resolve hostnames or port names.-v,-vv,-vvv: Increase verbosity.-w <file>: Write raw packets to a file for later analysis (e.g., in Wireshark).-r <file>: Read packets from a file.-s <snaplen>: Set the snapshot length (the number of bytes to capture per packet).-s 0captures the entire packet.port <port>: Filter by port number.host <host>: Filter by host.src <host>: Filter by source host.dst <host>: Filter by destination host.tcp,udp,icmp: Filter by protocol.
lsof:-i: List open internet files.-i :<port>: List processes using a specific port.-p <pid>: List files opened by a specific process ID.
nc:-l: Listen for incoming connections.-p <port>: Specify the port to listen on or connect to.-v: Verbose output.-z: Zero-I/O mode (used for port scanning). Only checks if a port is open, doesn’t send data.-u: Use UDP instead of TCP.-w <seconds>: Timeout after a specified number of seconds.
nmap:-p <port(s)>: Specify the port(s) to scan. Can be a single port, a range (e.g.,1-100), or a comma-separated list.-sS: TCP SYN scan (stealth scan, requires root privileges).-sT: TCP connect scan (requires no special privileges).-sU: UDP scan.-O: Operating system detection.-v: Increase verbosity.-A: Aggressive scan (enables OS detection, version detection, script scanning, and traceroute). Use with caution.-T<0-5>: Timing template (0 = paranoid, 1 = sneaky, 2 = polite, 3 = normal, 4 = aggressive, 5 = insane). Higher numbers are faster but more likely to be detected.
5. Advanced Usage
netstat -antp | grep :80: Find the process ID (PID) and program name listening on port 80. (Linux)ss -ltnp | grep :22: Find the process ID (PID) and program name listening on port 22 (SSH). (Linux)tcpdump -i eth0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' -w http.pcap: Capture HTTP traffic with payload and save it to a file (useful for analyzing web requests and responses).lsof -iTCP -sTCP:LISTEN: List all processes listening on TCP ports.nc -l -p 12345 > received_file.txt: Listen on port 12345 and save the received data toreceived_file.txt.cat file.txt | nc 192.168.1.100 12345: Send the contents offile.txtto 192.168.1.100 on port 12345.nmap -sV -p 22,80,443 192.168.1.1: Perform version detection on ports 22, 80, and 443 on 192.168.1.1. This attempts to determine the specific software versions running on those ports.nmap -sP 192.168.1.0/24: Ping scan to discover all active hosts on the 192.168.1.0/24 network.- Combining tools:
tcpdump -i eth0 port 80 | grep 'HTTP/1.1'- capture http traffic and then grep it for HTTP/1.1 to look for specific response headers.
6. Troubleshooting Scenarios
- Problem: A service isn’t accessible on a server.
- Solution: Use
netstat -anorss -ltto check if the service is listening on the correct port and interface. Uselsof -i :<port>to verify that the correct process is bound to the port. Usetcpdumpto check if traffic is reaching the server. Check firewall rules.
- Solution: Use
- Problem: High network traffic.
- Solution: Use
netstat -anorss -sto get a summary of network connections. Usetcpdumpto capture and analyze the traffic to identify the source and destination of the traffic and the protocols being used.
- Solution: Use
- Problem: A specific port is being blocked.
- Solution: Use
nc -zv <host> <port>to test connectivity to the port. If the connection fails, check firewall rules on both the client and server. Usetcpdumpto see if traffic is being dropped.
- Solution: Use
- Problem: Identifying a rogue process consuming bandwidth.
- Solution: Use
netstat -antporss -ltnpto identify processes with high connection counts. Then, investigate those processes.tcpdumpcan help analyze the traffic generated by the process.
- Solution: Use
- Problem: DNS resolution issues.
- Solution:
netstat -anwill show numeric addresses. If you see connections failing to resolve, investigate DNS server settings and reachability.tcpdumpcan capture DNS queries and responses.
- Solution:
7. Output Interpretation
netstat/ssState Codes (TCP):LISTEN: The socket is listening for incoming connections.ESTABLISHED: A connection has been established.SYN_SENT: The socket is actively attempting to establish a connection.SYN_RECV: A connection request has been received.FIN_WAIT1,FIN_WAIT2: The socket is waiting for the other end to close the connection.TIME_WAIT: The socket is waiting after closing a connection to handle delayed packets.CLOSE_WAIT: The socket is waiting for the application to close the connection.CLOSED: The socket is closed.
tcpdump: The output shows the captured packets, including source and destination IP addresses, ports, protocols, and flags. Understanding TCP flags (SYN, ACK, FIN, RST) is essential for diagnosing connection issues.nmap: The output shows the status of each scanned port (open, closed, filtered). “Open” means a service is listening on the port. “Closed” means no service is listening. “Filtered” means a firewall is blocking the port, preventing nmap from determining its status.
8. Security Considerations
tcpdump: Capturing network traffic can expose sensitive information (passwords, credit card numbers). Use filters carefully to minimize the amount of data captured and store capture files securely. Disable promiscuous mode when not needed.nmap: Scanning networks without authorization is illegal and unethical. Usenmapresponsibly and only on networks you own or have permission to scan. Avoid aggressive scans that can disrupt network services.nc:nccan be used to create backdoors or transfer malicious files. Secure your systems to prevent unauthorized use ofnc.- General: Avoid running network tools with root privileges unless absolutely necessary. Regularly review and update your security policies. Monitor network traffic for suspicious activity.
9. Platform Differences
- Linux:
netstatis often replaced byss.ipcommand provides more advanced network configuration options. - Windows:
netstatis available, butGet-NetTCPConnectionandGet-NetUDPListenerPowerShell cmdlets are preferred.tcpdumpcan be used with WinPcap or Npcap. Windows Firewall is enabled by default. - macOS:
netstatis available.tcpdumpis also available. macOS firewall is enabled by default.
Example Platform-Specific Commands
Windows (PowerShell):
# List all TCP connectionsGet-NetTCPConnection
# List all TCP connections with a specific stateGet-NetTCPConnection -State Established
# Find the process ID (PID) associated with a specific portGet-Process -Id (Get-NetTCPConnection -LocalPort 80).OwningProcessmacOS (Bash):
# List all listening TCP portsnetstat -an | grep ".LISTEN" | grep tcp
# Find the process ID (PID) associated with a specific portlsof -i :80This cheatsheet provides a solid foundation for using netstat and related tools for network monitoring and troubleshooting. Remember to adapt the commands and techniques to your specific environment and needs. Always prioritize security and responsible use.