Open Port Analysis with nmap and netstat
Introduction
Network security begins with understanding what services are exposed on your systems. Open ports represent potential entry points for attackers, and unmanaged or unnecessary open ports significantly expand your attack surface. Effective port analysis and management are fundamental security practices that every system administrator and security professional must master.
Two powerful tools dominate the landscape of port analysis: nmap (Network Mapper), the industry-standard external port scanner, and netstat, the built-in utility for examining local network connections. Together, these tools provide comprehensive visibility into your network exposure, active connections, and listening services, enabling you to identify security gaps, verify firewall configurations, and maintain a secure network posture.
This comprehensive guide covers everything from basic port scanning to advanced network reconnaissance techniques, including service detection, vulnerability assessment, and ongoing port monitoring. Whether you're conducting security audits, troubleshooting network issues, or hardening system security, this guide provides the knowledge and practical techniques needed for effective port analysis.
Understanding Port Analysis and Security Context
What Are Ports?
Network ports are virtual endpoints used by operating systems to manage network connections. Each port is identified by a number (0-65535) and associated with specific services or applications:
- Ports 0-1023: Well-known ports (HTTP/80, HTTPS/443, SSH/22)
- Ports 1024-49151: Registered ports (assigned to specific services)
- Ports 49152-65535: Dynamic/private ports (temporary connections)
Why Port Analysis Matters
Regular port analysis is critical for security:
- Attack surface reduction: Identify and close unnecessary open ports
- Security auditing: Verify only authorized services are exposed
- Compliance: Meet requirements for PCI DSS, HIPAA, NIST
- Vulnerability management: Detect outdated or vulnerable services
- Intrusion detection: Identify unauthorized services or backdoors
- Network troubleshooting: Diagnose connectivity and service issues
- Configuration validation: Verify firewall rules are effective
nmap vs. netstat
nmap (Network Mapper)
- External perspective (how attackers see your system)
- Scans remote hosts
- Service and version detection
- Operating system fingerprinting
- Vulnerability scanning capabilities
- Firewall evasion techniques
netstat (Network Statistics)
- Internal perspective (actual system state)
- Shows listening ports and active connections
- Process identification
- Routing table information
- Interface statistics
- No network traffic generated
Common Security Issues Discovered
Port analysis frequently reveals:
- Unnecessary services running (FTP, Telnet, old protocols)
- Services on non-standard ports
- Backdoors or unauthorized services
- Misconfigured firewalls
- Development services in production
- Vulnerable service versions
- Services bound to wrong interfaces
Legal and Ethical Considerations
IMPORTANT: Only scan systems you own or have explicit permission to scan. Unauthorized port scanning may be illegal and could be considered an attack attempt. Always:
- Obtain written permission for external scans
- Scan only your own infrastructure or with authorization
- Be aware of terms of service for cloud providers
- Document scanning activities for compliance
- Use caution with aggressive scanning options
Prerequisites
Before conducting port analysis, ensure you have:
System Requirements
- Operating System: Linux, macOS, or Windows
- Network Access: Connectivity to target systems
- Permissions: Root/administrator for some operations
- Resources: Adequate bandwidth for scanning
Required Knowledge
- Basic networking concepts (TCP/IP, ports, protocols)
- Command-line proficiency
- Understanding of common services and ports
- Basic security concepts
- Firewall fundamentals
Software Requirements
Install nmap:
Ubuntu/Debian:
sudo apt-get update
sudo apt-get install nmap
CentOS/RHEL:
sudo yum install nmap
macOS:
brew install nmap
Verify installation:
nmap --version
netstat availability:
netstat is typically pre-installed on most systems. On newer Linux distributions, it may be replaced by ss (socket statistics).
If netstat is missing:
sudo apt-get install net-tools # Ubuntu/Debian
sudo yum install net-tools # CentOS/RHEL
Optional Tools
Additional useful utilities:
# Install ss (modern netstat alternative)
# Usually included in iproute2 package
# Install lsof (list open files)
sudo apt-get install lsof
# Install tcpdump (packet capture)
sudo apt-get install tcpdump
Step-by-Step Port Analysis with nmap
Step 1: Basic nmap Scanning
Scan a single host:
nmap 192.168.1.100
Default scan checks most common 1,000 ports.
Scan multiple hosts:
nmap 192.168.1.100 192.168.1.101 192.168.1.102
Scan a range:
nmap 192.168.1.1-254
Scan a subnet:
nmap 192.168.1.0/24
Scan multiple subnets:
nmap 192.168.1.0/24 10.0.0.0/24
Step 2: Specify Scan Types
TCP Connect Scan (default without root):
nmap -sT 192.168.1.100
Completes full TCP handshake, more detectable.
TCP SYN Scan (stealth scan, requires root):
sudo nmap -sS 192.168.1.100
Sends SYN packets, doesn't complete handshake, harder to detect.
UDP Scan:
sudo nmap -sU 192.168.1.100
Scans UDP ports, slower than TCP scans.
Combined TCP and UDP:
sudo nmap -sS -sU 192.168.1.100
TCP ACK Scan (firewall mapping):
sudo nmap -sA 192.168.1.100
Determines firewall rules, doesn't determine open ports.
TCP Window Scan:
sudo nmap -sW 192.168.1.100
Similar to ACK but can sometimes differentiate open from closed.
Step 3: Port Specification
Scan specific port:
nmap -p 22 192.168.1.100
Scan multiple specific ports:
nmap -p 22,80,443 192.168.1.100
Scan port range:
nmap -p 1-1000 192.168.1.100
Scan all 65535 ports:
nmap -p- 192.168.1.100
Scan most common ports (fast):
nmap -F 192.168.1.100
Scan top N ports:
nmap --top-ports 100 192.168.1.100
Step 4: Service and Version Detection
Detect service versions:
nmap -sV 192.168.1.100
Example output:
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.5
80/tcp open http Apache httpd 2.4.41
443/tcp open ssl/http nginx 1.18.0
Aggressive version detection:
nmap -sV --version-intensity 9 192.168.1.100
Intensity: 0 (light) to 9 (comprehensive).
Version detection with OS fingerprinting:
sudo nmap -A 192.168.1.100
The -A flag enables OS detection, version detection, script scanning, and traceroute.
Step 5: Operating System Detection
OS fingerprinting:
sudo nmap -O 192.168.1.100
Aggressive OS detection:
sudo nmap -O --osscan-guess 192.168.1.100
Example output:
Running: Linux 5.X
OS CPE: cpe:/o:linux:linux_kernel:5
OS details: Linux 5.0 - 5.4
Step 6: NSE (Nmap Scripting Engine)
Run default scripts:
nmap -sC 192.168.1.100
Run specific script:
nmap --script=http-title 192.168.1.100
Run category of scripts:
nmap --script=vuln 192.168.1.100
Common useful scripts:
# HTTP enumeration
nmap --script=http-enum 192.168.1.100
# SSL certificate information
nmap --script=ssl-cert -p 443 192.168.1.100
# SMB enumeration
nmap --script=smb-os-discovery 192.168.1.100
# DNS information
nmap --script=dns-brute example.com
# Vulnerability scanning
nmap --script=vulners 192.168.1.100
List available scripts:
nmap --script-help "*"
Search for scripts:
nmap --script-help "*http*"
Step 7: Timing and Performance
Timing templates (T0-T5):
# Paranoid (slowest, stealthy)
nmap -T0 192.168.1.100
# Sneaky
nmap -T1 192.168.1.100
# Polite
nmap -T2 192.168.1.100
# Normal (default)
nmap -T3 192.168.1.100
# Aggressive (fast)
nmap -T4 192.168.1.100
# Insane (fastest, may miss results)
nmap -T5 192.168.1.100
Custom timing:
nmap --max-retries 1 --host-timeout 10m 192.168.1.0/24
Parallel scanning:
nmap --min-parallelism 100 192.168.1.0/24
Step 8: Output Formats
Normal output to file:
nmap -oN scan-results.txt 192.168.1.100
XML output (for parsing):
nmap -oX scan-results.xml 192.168.1.100
Grepable output:
nmap -oG scan-results.gnmap 192.168.1.100
All formats:
nmap -oA scan-results 192.168.1.100
Creates three files: .nmap, .xml, .gnmap
Step 9: Advanced Scanning Techniques
Idle/Zombie scan (ultra stealthy):
sudo nmap -sI zombie-host target-host
FTP bounce scan:
nmap -b ftp-server target-host
Fragmented packets (firewall evasion):
sudo nmap -f 192.168.1.100
Decoy scanning (hide your IP):
sudo nmap -D RND:10 192.168.1.100
Uses 10 random decoy IPs.
Spoof source IP:
sudo nmap -S spoofed-ip target-ip
Custom source port:
sudo nmap --source-port 53 192.168.1.100
Useful as some firewalls allow DNS (port 53).
Step-by-Step Port Analysis with netstat
Step 1: Basic netstat Usage
Show all connections:
netstat -a
Show only listening ports:
netstat -l
Show only TCP:
netstat -t
Show only UDP:
netstat -u
Common combination (listening TCP/UDP with numeric addresses):
netstat -tuln
Flags:
-t: TCP-u: UDP-l: Listening-n: Numeric (don't resolve names)
Step 2: Display Process Information
Show process IDs and names:
sudo netstat -tulnp
Example output:
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1234/sshd
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 5678/mysqld
tcp6 0 0 :::80 :::* LISTEN 9012/apache2
Filter by program:
sudo netstat -tulnp | grep ssh
Step 3: Show Active Connections
All active connections:
netstat -an
Active connections with process info:
sudo netstat -anp
Show established connections only:
netstat -ant | grep ESTABLISHED
Count connections by state:
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
Step 4: Network Statistics
Show network statistics:
netstat -s
Shows statistics for:
- IP packets
- TCP segments
- UDP datagrams
- ICMP messages
Show interface statistics:
netstat -i
Continuous interface statistics:
netstat -ic
Step 5: Routing Table
Display routing table:
netstat -r
Or:
netstat -rn
Show extended routing information:
netstat -rn --verbose
Step 6: Multicast Group Information
Show multicast group membership:
netstat -g
Step 7: Using ss (Modern Alternative)
ss is faster and provides more information than netstat:
Show all sockets:
ss -a
Listening sockets with process info:
sudo ss -tulnp
Show established connections:
ss -t state established
Show sockets in specific state:
ss -t state time-wait
ss -t state syn-sent
ss -t state syn-recv
Show summary:
ss -s
Filter by port:
ss -tuln sport = :80
Show memory usage per socket:
ss -tm
Step 8: Using lsof for Port Analysis
List all network connections:
sudo lsof -i
List specific port:
sudo lsof -i :80
List TCP connections:
sudo lsof -iTCP
List UDP connections:
sudo lsof -iUDP
Show what's using a specific port:
sudo lsof -i :22
List connections by user:
sudo lsof -i -u username
Exclude user:
sudo lsof -i -u ^root
Step 9: Combining Tools for Analysis
Find process listening on port:
sudo netstat -tulnp | grep :80
sudo ss -tulnp | grep :80
sudo lsof -i :80
Monitor new connections in real-time:
watch -n 1 'netstat -ant | grep ESTABLISHED | wc -l'
Find top connections by IP:
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
Detect port scanning attempts:
netstat -ant | grep SYN_RECV | wc -l
Advanced Port Analysis Techniques
1. Comprehensive Security Audit
Complete nmap security audit:
sudo nmap -sS -sV -O -A --script=vuln -p- -T4 -oA security-audit 192.168.1.100
This performs:
- SYN scan
- Version detection
- OS fingerprinting
- Aggressive detection
- Vulnerability scripts
- All ports
- Fast timing
- Output to all formats
2. Automated Monitoring Script
Create monitoring script:
#!/bin/bash
# port-monitor.sh
LOGFILE="/var/log/port-monitor.log"
PREVIOUS="/tmp/previous-ports.txt"
CURRENT="/tmp/current-ports.txt"
# Get current listening ports
sudo ss -tuln | grep LISTEN | awk '{print $5}' | sort > "$CURRENT"
# Compare with previous
if [ -f "$PREVIOUS" ]; then
DIFF=$(diff "$PREVIOUS" "$CURRENT")
if [ -n "$DIFF" ]; then
echo "$(date): Port changes detected" >> "$LOGFILE"
echo "$DIFF" >> "$LOGFILE"
# Send alert
echo "Port changes detected: $DIFF" | mail -s "Port Alert" [email protected]
fi
fi
# Update previous
cp "$CURRENT" "$PREVIOUS"
Add to cron:
*/5 * * * * /usr/local/bin/port-monitor.sh
3. Network Baseline Creation
Create baseline of expected services:
#!/bin/bash
# baseline-ports.sh
echo "Creating network baseline for $(hostname)"
echo "Date: $(date)"
echo ""
echo "=== Listening Services ==="
sudo ss -tulnp | grep LISTEN
echo ""
echo "=== External View ==="
nmap -sS -sV localhost
echo ""
echo "=== Process Details ==="
sudo lsof -i -n
Run monthly and compare:
diff baseline-2024-01.txt baseline-2024-02.txt
4. Stealth Scanning for Penetration Testing
Ultra-stealthy scan:
sudo nmap -sS -Pn -f --data-length 50 --scan-delay 10s -T1 --randomize-hosts target-list.txt
Options:
-Pn: Skip host discovery-f: Fragment packets--data-length 50: Add random data to packets--scan-delay 10s: Delay between probes-T1: Sneaky timing--randomize-hosts: Randomize target order
5. Vulnerability Assessment
Scan for known vulnerabilities:
nmap --script=vuln,exploit 192.168.1.100
Check SSL/TLS vulnerabilities:
nmap --script=ssl-enum-ciphers,ssl-heartbleed,ssl-poodle -p 443 192.168.1.100
Web application scanning:
nmap --script=http-vuln-* -p 80,443 192.168.1.100
6. Firewall Testing
Test firewall effectiveness:
# From outside network
sudo nmap -sS -p- external-ip
# From inside network
sudo nmap -sS -p- internal-ip
# Compare results to identify firewall gaps
ACK scan for firewall rules:
sudo nmap -sA -p 1-1000 192.168.1.100
7. Service Enumeration
HTTP enumeration:
nmap --script=http-enum,http-headers,http-methods,http-title -p 80,443 192.168.1.100
SMB enumeration:
nmap --script=smb-enum-shares,smb-enum-users,smb-os-discovery -p 445 192.168.1.100
SMTP enumeration:
nmap --script=smtp-enum-users,smtp-commands -p 25 192.168.1.100
8. Performance Analysis
Identify connection-heavy processes:
sudo ss -antp | awk '{print $6}' | grep -oP '(?<=pid=)[0-9]+' | sort | uniq -c | sort -rn | head
Monitor port exhaustion:
sudo ss -ant | grep -c TIME_WAIT
If this number is very high (>10000), you may be running out of ports.
Verification and Testing
Verify Open Ports Match Expectations
External verification:
nmap -sV -p 80,443,22 your-public-ip
Internal verification:
sudo ss -tulnp
Compare external and internal views
Test Service Accessibility
Test HTTP:
curl -I http://localhost
Test HTTPS:
curl -Ik https://localhost
Test SSH:
ssh -v localhost
Test MySQL:
mysql -h localhost -u root -p
Verify Firewall Rules
Check iptables:
sudo iptables -L -n -v
Check firewalld:
sudo firewall-cmd --list-all
Test blocked port:
nmap -p 3306 external-ip
Should show filtered or closed if firewall is working.
Performance Impact Testing
Baseline without scanning:
time curl http://localhost/large-file.zip > /dev/null
During scanning:
# Terminal 1
nmap -A localhost
# Terminal 2
time curl http://localhost/large-file.zip > /dev/null
Troubleshooting Common Issues
Issue 1: Port Appears Open in netstat But Closed in nmap
Symptoms: Discrepancy between internal and external views
Solutions:
-
Check if service is bound to localhost only:
sudo ss -tulnp | grep :3306If showing
127.0.0.1:3306, it's only accessible locally. -
Verify firewall rules:
sudo iptables -L -n | grep 3306 -
Check listening interface: Services may bind to specific interface.
Issue 2: nmap Says Port Filtered
Symptoms: Port shows as "filtered" instead of "open" or "closed"
Cause: Firewall is dropping packets
Solutions:
-
Verify with telnet:
telnet target-ip target-port -
Check firewall logs:
sudo tail -f /var/log/syslog | grep UFW -
Add firewall rule if needed:
sudo ufw allow from source-ip to any port target-port
Issue 3: netstat Shows Process as "-"
Symptoms: Process column shows hyphen instead of PID/name
Cause: Insufficient privileges
Solution:
sudo netstat -tulnp
Issue 4: Too Many TIME_WAIT Connections
Symptoms: High number of connections in TIME_WAIT state
Solutions:
-
Check count:
ss -ant | grep TIME_WAIT | wc -l -
Reduce TIME_WAIT timeout (if necessary):
sudo sysctl -w net.ipv4.tcp_fin_timeout=30 -
Enable socket reuse:
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
Issue 5: Port Already in Use
Symptoms: Cannot start service due to port conflict
Solutions:
-
Find what's using the port:
sudo lsof -i :80 sudo ss -tulnp | grep :80 -
Kill the process:
sudo kill -9 PID -
Or change service port in configuration
Issue 6: Incomplete nmap Results
Symptoms: nmap missing open ports that exist
Solutions:
-
Scan all ports:
nmap -p- target -
Try different scan type:
sudo nmap -sT target # Instead of -sS -
Increase timing:
nmap -T4 target -
Disable ping:
nmap -Pn target
Best Practices for Port Analysis
1. Regular Scanning Schedule
- Weekly: Internal port scans of critical servers
- Monthly: Complete network inventory scans
- Quarterly: External penetration testing perspective
- After changes: Scan after any network/service changes
- Continuous: Automated monitoring for unauthorized services
2. Documentation
- Baseline inventory: Document all expected open ports
- Service ownership: Track which team owns each service
- Change management: Log all port/service changes
- Exception tracking: Document approved non-standard ports
- Scan results: Retain scan results for trend analysis
3. Security Hardening
- Close unnecessary ports: Disable unused services
- Bind to specific interfaces: Don't use 0.0.0.0 unnecessarily
- Use non-standard ports: For additional obscurity (not security)
- Implement firewall rules: Default deny, explicit allow
- Regular updates: Keep services updated to patch vulnerabilities
4. Monitoring and Alerting
- Automated scanning: Schedule regular port scans
- Change detection: Alert on unexpected open ports
- Connection monitoring: Track unusual connection patterns
- Log aggregation: Centralize port/connection logs
- Threshold alerts: Alert on excessive connections
5. Compliance and Auditing
- Policy enforcement: Ensure port policies are followed
- Audit trails: Maintain logs of scan results
- Quarterly reviews: Review all open ports and services
- Penetration testing: Include port analysis in pentests
- Documentation: Keep port inventory current
6. Operational Practices
- Test before production: Scan staging environments
- Coordinate scans: Notify teams before scanning
- Respect rate limits: Don't overwhelm networks with scans
- Verify changes: Scan after configuration changes
- Emergency procedures: Know how to quickly close ports
7. Tool Selection
- Use nmap for: External perspective, service detection
- Use netstat/ss for: Internal state, process identification
- Use lsof for: Detailed process/file descriptor information
- Use tcpdump for: Packet-level analysis
- Use multiple tools: Cross-verify results
Conclusion
Effective port analysis using nmap and netstat is fundamental to maintaining secure systems and networks. These powerful tools provide complementary perspectives—nmap reveals how attackers see your systems, while netstat shows the internal reality of network services and connections. Together, they form an essential toolkit for security professionals and system administrators.
Key takeaways:
- Regular scanning: Make port analysis a routine practice
- Multiple perspectives: Use both external (nmap) and internal (netstat) views
- Close unnecessary ports: Every open port is a potential attack vector
- Monitor continuously: Automate detection of unexpected services
- Document everything: Maintain inventory of expected services
- Stay updated: Keep scanning tools and knowledge current
Port analysis is particularly valuable for:
- Security audits and assessments
- Compliance verification (PCI DSS, HIPAA, SOC 2)
- Incident response and forensics
- Network troubleshooting
- Change verification
- Attack surface reduction
Remember that port analysis is not a one-time activity but an ongoing process. Establish regular scanning schedules, automate monitoring where possible, and maintain detailed documentation of expected services. Combined with proper firewall configuration, service hardening, and security monitoring, effective port analysis forms a critical component of defense-in-depth security.
Start with understanding your current exposure, establish baselines, implement monitoring, and continuously refine your approach. With proper implementation and maintenance, port analysis becomes an invaluable early-warning system that helps prevent security incidents before they occur. The time invested in mastering nmap and netstat pays significant dividends in security posture, compliance assurance, and operational excellence.


