Ephemeral ports (also called dynamic ports) are temporary TCP/UDP ports allocated automatically by the Linux kernel when a client application needs to establish an outbound connection. These ports typically range between 32768-60999 (default in most Linux distributions) and are released after the connection terminates.
When your system runs low on ephemeral ports, you'll encounter "Address already in use" or "Cannot assign requested address" errors. Common scenarios that exhaust ephemeral ports include:
- High-frequency connection establishments (e.g., microservices communication)
- Connection leaks in applications
- TCP TIME_WAIT state buildup
Here are several ways to monitor available ephemeral ports:
1. Viewing Port Range Configuration
First, check your system's configured port range:
cat /proc/sys/net/ipv4/ip_local_port_range
# Typical output: 32768 60999
2. Counting Currently Used Ephemeral Ports
Count active connections using ephemeral ports:
ss -tan | awk '{print $4}' | grep -E ":(3276[8-9]|3[2-9][0-9]{3}|[4-5][0-9]{4}|60[0-9]{3})$" | wc -l
This command counts all connections using ports within the ephemeral range.
3. Available Ports Calculation
Calculate remaining available ports:
EPHEMERAL_RANGE=$(cat /proc/sys/net/ipv4/ip_local_port_range)
USED_PORTS=$(ss -tan | awk '{print $4}' | grep -E ":(3276[8-9]|3[2-9][0-9]{3}|[4-5][0-9]{4}|60[0-9]{3})$" | wc -l)
TOTAL_PORTS=$(( ${EPHEMERAL_RANGE#* } - ${EPHEMERAL_RANGE% *} + 1 ))
echo "Available ephemeral ports: $(( TOTAL_PORTS - USED_PORTS ))/$TOTAL_PORTS"
Create a monitoring script to alert when ports are running low:
#!/bin/bash
# Threshold percentage (15% remaining)
WARNING_THRESHOLD=15
# Get port range
read LOWER UPPER < /proc/sys/net/ipv4/ip_local_port_range
TOTAL=$((UPPER - LOWER + 1))
# Count used ports
USED=$(ss -tan | awk '{print $4}' | grep -E ":(3276[8-9]|3[2-9][0-9]{3}|[4-5][0-9]{4}|60[0-9]{3})$" | wc -l)
# Calculate percentage remaining
AVAILABLE=$((TOTAL - USED))
PERCENT=$((AVAILABLE * 100 / TOTAL))
if [ $PERCENT -le $WARNING_THRESHOLD ]; then
echo "WARNING: Only $PERCENT% ephemeral ports remaining ($AVAILABLE/$TOTAL)" >&2
exit 1
else
echo "OK: $PERCENT% ephemeral ports available ($AVAILABLE/$TOTAL)"
exit 0
fi
If you frequently run out of ports, consider these kernel parameter adjustments:
# Increase port range
sudo sysctl -w net.ipv4.ip_local_port_range="15000 65000"
# Reduce TIME_WAIT duration (default 60s)
sudo sysctl -w net.ipv4.tcp_fin_timeout=30
# Enable port reuse (requires application support)
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
When ports are exhausted, investigate connections:
# Show all active connections with ephemeral ports
ss -tanp | grep -E ":(3276[8-9]|3[2-9][0-9]{3}|[4-5][0-9]{4}|60[0-9]{3})$"
# Group by process
ss -tanp | grep -E ":(3276[8-9]|3[2-9][0-9]{3}|[4-5][0-9]{4}|60[0-9]{3})$" | awk '{print $6}' | sort | uniq -c | sort -nr
On Linux systems, ephemeral ports (also called dynamic ports) are temporary ports used for outbound connections. These ports are automatically allocated by the kernel from a predefined range when establishing connections. The default range is typically:
cat /proc/sys/net/ipv4/ip_local_port_range
# Output example: 32768 60999
To monitor currently used ephemeral ports, you can use these commands:
# Check TCP connections using ephemeral ports
ss -tan | awk '{print $4}' | grep -E '[0-9]+$' | awk -F: '{print $NF}' | sort -n | uniq -c
# Count currently used ephemeral ports
ss -tan | awk '$1 == "tcp" && $4 !~ /:(22|80|443)/ {print $4}' | awk -F: '{print $NF}' | sort -u | wc -l
This script calculates available ports in real-time:
#!/bin/bash
# Get port range
read LOWER UPPER < /proc/sys/net/ipv4/ip_local_port_range
# Count used ports
USED=$(ss -tan | awk '$1 == "tcp" && $4 !~ /:(22|80|443)/ {print $4}' | awk -F: '{print $NF}' | sort -u | wc -l)
# Calculate available
TOTAL=$((UPPER - LOWER + 1))
AVAILABLE=$((TOTAL - USED))
echo "Ephemeral port range: $LOWER - $UPPER"
echo "Used ports: $USED"
echo "Available ports: $AVAILABLE ($((AVAILABLE * 100 / TOTAL))%)"
For production systems, consider setting up monitoring with this Python script:
import subprocess
import re
def check_ephemeral_ports():
# Get port range
with open('/proc/sys/net/ipv4/ip_local_port_range', 'r') as f:
lower, upper = map(int, f.read().split())
# Get used ports
cmd = "ss -tan state established | awk '{print $4}' | grep -oE '[0-9]+$' | sort -u"
output = subprocess.check_output(cmd, shell=True).decode()
used_ports = set(map(int, output.split()))
# Filter ephemeral ports
ephemeral_used = [p for p in used_ports if lower <= p <= upper]
available = (upper - lower + 1) - len(ephemeral_used)
percentage = (available / (upper - lower + 1)) * 100
return {
'range': (lower, upper),
'used': len(ephemeral_used),
'available': available,
'percentage': percentage
}
if __name__ == "__main__":
stats = check_ephemeral_ports()
print(f"Ephemeral port status: {stats['available']}/{stats['range'][1]-stats['range'][0]+1} available ({stats['percentage']:.1f}%)")
If you frequently run out of ports, consider adjusting these sysctl settings:
# Increase port range
sudo sysctl -w net.ipv4.ip_local_port_range="10000 65000"
# Enable port reuse (careful with this)
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
# Reduce TIME_WAIT duration (default is 60 seconds)
sudo sysctl -w net.ipv4.tcp_fin_timeout=30
To make changes permanent, add them to /etc/sysctl.conf:
net.ipv4.ip_local_port_range = 10000 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
Then apply with:
sudo sysctl -p
For detailed tracking, use this kernel monitoring command:
watch -n 1 'cat /proc/net/sockstat{,6} | grep -E "TCP:|inuse"'