🛠️ToolsShed

Netstat Commands Reference

Complete netstat and ss command reference for Linux, macOS, and Windows with searchable examples.

List all connections

netstat
netstat -a
ss (modern)
ss -a

List listening ports (TCP+UDP)

netstat
netstat -tuln
ss (modern)
ss -tuln

Show TCP connections

netstat
netstat -tn
ss (modern)
ss -tn

Show UDP connections

netstat
netstat -un
ss (modern)
ss -un

Show process PIDs

netstat
netstat -tulnp
ss (modern)
ss -tulnp

Linux/macOS may require root for PID visibility

Show routing table

netstat
netstat -r
ss (modern)
ip route

Show network statistics

netstat
netstat -s
ss (modern)
ss -s

Count connections by state

netstat
netstat -an | awk '{print $6}' | sort | uniq -c | sort -rn
ss (modern)
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c

Find process using a port

netstat
netstat -tulnp | grep :8080
ss (modern)
ss -tulnp | grep :8080

Replace 8080 with your port number

Show socket summary

netstat
netstat -i
ss (modern)
ss -i
ss NetstatCommandsReference.ssNote

Perguntas Frequentes

Implementação de Código

import subprocess
import platform

def run_netstat(args: list[str]) -> str:
    """Run netstat command and return output."""
    try:
        result = subprocess.run(["netstat"] + args, capture_output=True, text=True, timeout=10)
        return result.stdout
    except FileNotFoundError:
        # Try ss on Linux if netstat not found
        if platform.system() == "Linux":
            result = subprocess.run(["ss"] + args, capture_output=True, text=True, timeout=10)
            return result.stdout
        return "netstat not found"

# Show all listening TCP ports
print("=== Listening TCP ports ===")
system = platform.system()
if system == "Linux":
    print(run_netstat(["-tlnp"]))   # or ss -tlnp
elif system == "Darwin":  # macOS
    print(run_netstat(["-an", "-p", "tcp"]))
elif system == "Windows":
    print(run_netstat(["-ano", "-p", "TCP"]))

# Parse listening ports
def get_listening_ports() -> list[dict]:
    """Parse ss output on Linux to get listening ports."""
    result = subprocess.run(["ss", "-tlnp"], capture_output=True, text=True)
    ports = []
    for line in result.stdout.splitlines()[1:]:
        parts = line.split()
        if len(parts) >= 4 and parts[0] == "LISTEN":
            ports.append({"state": parts[0], "local": parts[3], "process": parts[6] if len(parts) > 6 else ""})
    return ports

if system == "Linux":
    for p in get_listening_ports():
        print(p)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.