How to show socket statistics → ss

How to Show Socket Statistics → ss Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding the ss Command](#understanding-the-ss-command) 4. [Basic ss Command Usage](#basic-ss-command-usage) 5. [Advanced ss Options and Filters](#advanced-ss-options-and-filters) 6. [Practical Examples and Use Cases](#practical-examples-and-use-cases) 7. [Comparing ss with netstat](#comparing-ss-with-netstat) 8. [Troubleshooting Common Issues](#troubleshooting-common-issues) 9. [Best Practices and Professional Tips](#best-practices-and-professional-tips) 10. [Conclusion](#conclusion) Introduction The `ss` (socket statistics) command is a powerful utility for displaying detailed information about network sockets on Linux systems. As the modern replacement for the deprecated `netstat` command, `ss` provides faster performance and more comprehensive socket information, making it an essential tool for system administrators, network engineers, and developers who need to monitor network connections, diagnose connectivity issues, and analyze system performance. In this comprehensive guide, you'll learn how to effectively use the `ss` command to examine socket statistics, filter results for specific protocols and states, troubleshoot network issues, and implement best practices for network monitoring. Whether you're a beginner looking to understand basic socket monitoring or an advanced user seeking to master complex filtering techniques, this article will provide you with the knowledge and practical examples needed to leverage the full power of the `ss` command. Prerequisites Before diving into socket statistics with the `ss` command, ensure you have the following requirements: System Requirements - Linux-based operating system (Ubuntu, CentOS, RHEL, Debian, etc.) - Terminal access with command-line privileges - Basic understanding of networking concepts (TCP, UDP, sockets, ports) Software Requirements - The `iproute2` package (usually pre-installed on modern Linux distributions) - Root or sudo privileges for certain advanced operations Knowledge Prerequisites - Familiarity with basic Linux command-line operations - Understanding of network protocols and port concepts - Basic knowledge of process management in Linux To verify that `ss` is available on your system, run: ```bash ss --version ``` If the command is not found, install the `iproute2` package: ```bash Ubuntu/Debian sudo apt-get install iproute2 CentOS/RHEL/Fedora sudo yum install iproute2 or sudo dnf install iproute2 ``` Understanding the ss Command The `ss` command stands for "socket statistics" and is part of the iproute2 package. It provides detailed information about network sockets, including their state, local and remote addresses, process information, and various statistics. Key Advantages of ss Over netstat 1. Performance: `ss` is significantly faster than `netstat`, especially on systems with many connections 2. Detailed Information: Provides more comprehensive socket statistics and kernel information 3. Better Filtering: Offers advanced filtering capabilities with more intuitive syntax 4. Active Development: Actively maintained and updated, unlike the deprecated `netstat` 5. Memory Efficiency: Uses less system resources when displaying socket information Socket States Understanding socket states is crucial for interpreting `ss` output: - LISTEN: Socket is listening for incoming connections - ESTABLISHED: Connection is established and active - TIME-WAIT: Connection is closed but waiting for remote shutdown - CLOSE-WAIT: Remote end has closed the connection - SYN-SENT: Attempting to establish connection - SYN-RECV: Connection request received from remote host - FIN-WAIT-1: Connection is closing, waiting for remote acknowledgment - FIN-WAIT-2: Connection is closed, waiting for remote shutdown - CLOSING: Both sides are closing simultaneously - CLOSED: Socket is not being used Basic ss Command Usage Default Output Running `ss` without any options displays all non-listening sockets: ```bash ss ``` Sample output: ``` Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port u_str ESTAB 0 0 /run/systemd/journal/stdout 23159 * 23158 u_str ESTAB 0 0 @/tmp/.X11-unix/X0 19825 * 19824 tcp ESTAB 0 0 192.168.1.100:22 192.168.1.50:54321 ``` Common Basic Options Show All Sockets ```bash ss -a ``` Show Listening Sockets Only ```bash ss -l ``` Show TCP Sockets ```bash ss -t ``` Show UDP Sockets ```bash ss -u ``` Show Process Information ```bash ss -p ``` Show Numerical Addresses (Don't Resolve Hostnames) ```bash ss -n ``` Combine Options ```bash ss -tuln ``` This shows TCP and UDP listening sockets with numerical addresses. Understanding the Output Format The `ss` command output contains several columns: - Netid: Network namespace identifier (tcp, udp, u_str for Unix sockets) - State: Current state of the socket - Recv-Q: Receive queue size - Send-Q: Send queue size - Local Address:Port: Local IP address and port number - Peer Address:Port: Remote IP address and port number - Process: Process information (when using -p option) Advanced ss Options and Filters Extended Information Show Extended Socket Information ```bash ss -e ``` Show Memory Usage ```bash ss -m ``` Show Timer Information ```bash ss -o ``` Show Socket Statistics ```bash ss -s ``` Sample statistics output: ``` Total: 1831 (kernel 2147) TCP: 12 (estab 4, closed 2, orphaned 0, synrecv 0, timewait 2/0), ports 0 Transport Total IP IPv6 * 2147 - - RAW 2 1 1 UDP 8 6 2 TCP 10 8 2 INET 20 15 5 FRAG 0 0 0 ``` Protocol-Specific Options Show Only IPv4 Sockets ```bash ss -4 ``` Show Only IPv6 Sockets ```bash ss -6 ``` Show Unix Domain Sockets ```bash ss -x ``` Show Raw Sockets ```bash ss -w ``` State Filtering You can filter sockets by their connection state: ```bash Show only established connections ss state established Show only listening sockets ss state listening Show multiple states ss state established state syn-sent Show all except time-wait ss exclude time-wait ``` Port and Address Filtering Filter by Specific Port ```bash Show connections on port 22 (SSH) ss -tuln sport = :22 Show connections to port 80 (HTTP) ss -tuln dport = :80 ``` Filter by Port Range ```bash Show connections on ports 1000-2000 ss -tuln sport ge :1000 and sport le :2000 ``` Filter by IP Address ```bash Show connections to specific IP ss dst 192.168.1.100 Show connections from specific IP ss src 192.168.1.50 ``` Advanced Filtering Examples Complex Filter Combinations ```bash TCP connections on port 80 or 443 ss -t '( dport = :80 or dport = :443 )' Established connections excluding localhost ss -t state established '( not dst 127.0.0.1 )' UDP sockets with high receive queue ss -u 'sport > :1024 and recvq > 0' ``` Practical Examples and Use Cases System Administration Tasks Monitor Web Server Connections ```bash Check HTTP/HTTPS connections ss -tuln | grep -E ':(80|443|8080|8443)' Monitor active web connections with process info ss -tp state established '( dport = :80 or dport = :443 )' ``` Database Connection Monitoring ```bash MySQL connections ss -tp sport = :3306 PostgreSQL connections ss -tp sport = :5432 MongoDB connections ss -tp sport = :27017 ``` SSH Connection Analysis ```bash Show all SSH connections ss -tp sport = :22 Count active SSH sessions ss -t state established sport = :22 | wc -l ``` Network Troubleshooting Identify Port Conflicts ```bash Check if a port is already in use ss -tuln | grep :8080 Find what process is using a specific port ss -tlnp | grep :3000 ``` Analyze Connection States ```bash Check for connections in TIME-WAIT state ss -t state time-wait Monitor for failed connection attempts ss -t state syn-sent Check for half-open connections ss -t state close-wait ``` Network Performance Analysis ```bash Show connections with data in send/receive queues ss -t '( recvq > 0 or sendq > 0 )' Monitor high-bandwidth connections ss -i state established ``` Development and Debugging Application Socket Monitoring ```bash Monitor sockets for specific application ss -tp | grep python Check Docker container connections ss -tp | grep docker Monitor Node.js application sockets ss -tlnp | grep node ``` Local Development Server Monitoring ```bash Check development servers ss -tuln | grep -E ':(3000|8000|8080|9000)' Monitor localhost connections only ss -tuln src 127.0.0.1 ``` Security Monitoring Identify Suspicious Connections ```bash Monitor connections to unusual ports ss -t '( dport > :10000 )' Check for connections to external IPs on sensitive ports ss -t state established '( not dst 127.0.0.1 and not dst 192.168.0.0/16 )' Monitor raw sockets (potential security concern) ss -w -p ``` Audit Listening Services ```bash List all listening services ss -tuln Check for services listening on all interfaces ss -tuln | grep '0.0.0.0\|:::' Verify expected services only ss -tlnp | grep -v -E ':(22|80|443)' | grep LISTEN ``` Comparing ss with netstat Performance Comparison The `ss` command significantly outperforms `netstat`, especially on systems with many connections: ```bash Time comparison example time netstat -tuln time ss -tuln ``` Feature Comparison | Feature | ss | netstat | |---------|----|---------| | Speed | Fast | Slow | | Filtering | Advanced | Basic | | Socket Details | Comprehensive | Limited | | Memory Usage | Low | High | | Development Status | Active | Deprecated | | Kernel Integration | Direct | Indirect | Migration Examples Common netstat to ss Conversions ```bash Show all listening ports netstat: netstat -tuln ss equivalent: ss -tuln Show process information netstat: netstat -tulnp ss equivalent: ss -tulnp Show established connections netstat: netstat -tun | grep ESTABLISHED ss equivalent: ss -tu state established Show statistics netstat: netstat -s ss equivalent: ss -s ``` Troubleshooting Common Issues Permission Issues Problem: Cannot See Process Information ```bash Error: process info not shown ss -p ``` Solution: Run with sudo privileges: ```bash sudo ss -p ``` Problem: Access Denied for Certain Sockets Solution: Use appropriate privileges or check system security policies: ```bash Check SELinux status sestatus Temporary disable if necessary (not recommended for production) sudo setenforce 0 ``` Output Interpretation Issues Problem: Confusing Socket States Solution: Use descriptive filtering and documentation: ```bash Add comments to commands ss -t state established # Show only active connections ss -t state time-wait # Show connections in cleanup phase ``` Problem: Too Much Output Solution: Use specific filters and pagination: ```bash Limit output with head ss -tuln | head -20 Use specific filters ss -t state established dst 192.168.1.0/24 Pipe to less for pagination ss -a | less ``` Performance Issues Problem: ss Command Running Slowly Solution: Use specific options to reduce processing: ```bash Use -n to avoid DNS resolution ss -tuln Limit to specific protocols ss -t # TCP only instead of all protocols Use specific state filters ss -t state established # Instead of all states ``` Problem: High System Load When Running ss Solution: Optimize command usage: ```bash Avoid frequent polling watch -n 5 'ss -s' # Every 5 seconds instead of continuous Use targeted queries ss -tp sport = :80 # Specific port instead of all ports ``` Common Error Messages "ss: command not found" Solution: Install iproute2 package: ```bash Ubuntu/Debian sudo apt-get update && sudo apt-get install iproute2 CentOS/RHEL sudo yum install iproute2 ``` "Cannot open netlink socket" Solution: Check system permissions and network namespace: ```bash Check current namespace ip netns list Run in root namespace if needed sudo ss -tuln ``` Best Practices and Professional Tips Monitoring and Automation Create Monitoring Scripts ```bash #!/bin/bash socket_monitor.sh - Monitor critical services echo "=== Web Server Status ===" ss -tlnp | grep -E ':(80|443)' echo "=== Database Connections ===" ss -tp sport = :3306 | wc -l echo "=== SSH Sessions ===" ss -tp sport = :22 state established | wc -l echo "=== System Socket Summary ===" ss -s ``` Use with System Monitoring Tools ```bash Integration with cron for regular monitoring Add to crontab: /5 * /usr/local/bin/socket_monitor.sh >> /var/log/socket_monitor.log Integration with systemd timers Create socket-monitor.service and socket-monitor.timer ``` Performance Optimization Efficient Command Usage ```bash Good: Specific and fast ss -tlnp sport = :80 Avoid: Broad and slow ss -ap | grep :80 Good: Direct state filtering ss -t state established Avoid: Post-processing filtering ss -t | grep ESTABLISHED ``` Batch Operations ```bash Collect multiple metrics efficiently { echo "Listening services:" ss -tlnp echo "Active connections:" ss -t state established echo "Socket statistics:" ss -s } > socket_report.txt ``` Security Considerations Regular Security Audits ```bash Check for unexpected listening services ss -tlnp | grep -v -E ':(22|80|443|25|53)' | grep LISTEN Monitor external connections ss -tp state established '( not dst 127.0.0.0/8 and not dst 192.168.0.0/16 )' Check for privileged port usage ss -tlnp | awk '$5 ~ /:([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|10[01][0-9]|102[0-3])$/' ``` Documentation and Logging ```bash Document expected services cat > /etc/expected_services.txt << EOF Expected listening services 22/tcp - SSH 80/tcp - HTTP 443/tcp - HTTPS EOF Create baseline reports ss -tlnp > /var/log/baseline_sockets_$(date +%Y%m%d).log ``` Advanced Usage Patterns Custom Aliases ```bash Add to ~/.bashrc alias ss-web='ss -tlnp | grep -E ":(80|443|8080|8443)"' alias ss-db='ss -tlnp | grep -E ":(3306|5432|27017|6379)"' alias ss-active='ss -tp state established' alias ss-listen='ss -tlnp' ``` Integration with Other Tools ```bash Combine with awk for custom formatting ss -tlnp | awk '/LISTEN/ {print $1, $5, $7}' Combine with jq for JSON output (requires additional processing) ss -tlnp | python3 -c " import sys, json Process ss output into JSON format (Custom script implementation) " Integration with monitoring systems ss -s | grep TCP | awk '{print "tcp.established", $4}' | cut -d',' -f1 ``` Troubleshooting Workflows Systematic Network Diagnosis ```bash #!/bin/bash network_diagnosis.sh echo "1. Check listening services:" ss -tlnp echo "2. Check active connections:" ss -tp state established echo "3. Check for connection issues:" ss -t state syn-sent state syn-recv echo "4. Check system socket health:" ss -s echo "5. Check for high queue usage:" ss -t '( recvq > 0 or sendq > 0 )' ``` Application-Specific Monitoring ```bash Web application monitoring monitor_webapp() { local app_port=$1 echo "Monitoring application on port $app_port" echo "Listening status:" ss -tlnp sport = :$app_port echo "Active connections:" ss -tp sport = :$app_port state established echo "Connection count:" ss -t sport = :$app_port state established | wc -l } Usage: monitor_webapp 8080 ``` Conclusion The `ss` command is an indispensable tool for modern Linux system administration, network monitoring, and troubleshooting. Throughout this comprehensive guide, we've explored its extensive capabilities, from basic socket listing to advanced filtering and monitoring techniques. Key Takeaways 1. Performance Advantage: The `ss` command offers significant performance improvements over the deprecated `netstat`, making it the preferred choice for socket statistics on modern Linux systems. 2. Comprehensive Information: Beyond basic connection details, `ss` provides extensive socket statistics, memory usage information, and detailed process associations that are crucial for system analysis. 3. Advanced Filtering: The powerful filtering capabilities allow for precise socket selection based on states, addresses, ports, and various other criteria, enabling targeted monitoring and troubleshooting. 4. Versatile Applications: From security auditing and performance monitoring to development debugging and system administration, `ss` serves multiple professional use cases effectively. Next Steps To further enhance your network monitoring and system administration skills: 1. Practice Regular Monitoring: Implement regular socket monitoring in your system maintenance routines using the examples and scripts provided in this guide. 2. Explore Integration Options: Consider integrating `ss` with monitoring systems like Nagios, Zabbix, or Prometheus for automated network health monitoring. 3. Develop Custom Scripts: Create application-specific monitoring scripts that leverage `ss` for your particular environment and requirements. 4. Study Network Security: Use `ss` as part of your security toolkit to regularly audit listening services and monitor for suspicious network activity. 5. Stay Updated: Keep your iproute2 package updated to benefit from the latest features and improvements in the `ss` command. By mastering the `ss` command and implementing the best practices outlined in this guide, you'll have a powerful tool at your disposal for maintaining healthy, secure, and well-monitored network infrastructure. The investment in learning these techniques will pay dividends in your ability to quickly diagnose network issues, optimize system performance, and maintain robust security postures across your Linux environments.