Blog / Linux/ Essential Commands for Monitoring Server TCP Connections

Essential Commands for Monitoring Server TCP Connections

关于服务器TCP连接的数量统计命令详解

1. Viewing IP Connections to the Server

Use the netstat command to view the current network connection status of the system.

netstat -an

2. Counting TCP Connections

2.1 Count Connections on Port 80

This command counts all connections related to port 80 (including LISTEN, ESTABLISHED, etc.).

netstat -nat | grep -i "80" | wc -l

2.2 Count HTTP Service Processes

This command counts the number of processes named "httpd", typically used for Apache servers.

ps -ef | grep httpd | wc -l

2.3 Count ESTABLISHED Connections

This command counts all established TCP connections.

netstat -na | grep ESTABLISHED | wc -l

2.4 Find IPs with the Most Connections

This command identifies the IP address with the most established connections, useful for troubleshooting abnormal traffic.

netstat -na | grep ESTABLISHED | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -rn

Similarly, to find IPs with connections in the SYN state:

netstat -na | grep SYN | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -rn

3. Apache Server Statistics

3.1 View Current Apache Concurrent Connections

This command counts established connections to the Apache service, which can be compared to the MaxClients parameter in the configuration.

netstat -an | grep ESTABLISHED | wc -l

3.2 View Apache Process Count

Both commands below can be used to count httpd processes, suitable for prefork and other modes.

ps aux | grep httpd | wc -l
# or
ps -ef | grep httpd | wc -l

The returned number roughly indicates the current number of concurrent requests Apache can handle.

3.3 View Total Requests on Port 80

netstat -nat | grep -i "80" | wc -l

3.4 View Total Established Connections

netstat -na | grep ESTABLISHED | wc -l

3.5 View Detailed Established Connection Records

netstat -nat | grep ESTABLISHED

4. Viewing TCP Connection State Distribution

A very practical command to count and list all TCP connection states and their quantities.

netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

Example output:

TIME_WAIT 8947
FIN_WAIT1 15
FIN_WAIT2 1
ESTABLISHED 55
SYN_RECV 21
CLOSING 2
LAST_ACK 4

TCP Connection State Details

  • LISTEN: Listening for connection requests from remote TCP ports.
  • SYN-SENT: Waiting for a matching connection request after sending one.
  • SYN-RECEIVED: Waiting for confirmation of a connection request after receiving and sending one.
  • ESTABLISHED: An open connection with normal data transfer in progress.
  • FIN-WAIT-1: Waiting for a remote TCP connection termination request, or confirmation of a previously sent termination request.
  • FIN-WAIT-2: Waiting for a connection termination request from the remote TCP.
  • CLOSE-WAIT: Waiting for a connection termination request from the local user.
  • CLOSING: Both sides are attempting to close, waiting for remote TCP confirmation of termination.
  • LAST-ACK: Waiting for confirmation of the original connection termination request sent to the remote TCP.
  • TIME-WAIT: Waiting long enough (2MSL) to ensure the remote TCP received the termination request confirmation.
  • CLOSED: No connection state.

For monitoring:

  • SYN_RECV indicates requests waiting to be processed; too many may indicate a SYN attack.
  • ESTABLISHED indicates the number of connections in normal data transfer state.
  • TIME_WAIT indicates requests that are finished, waiting for timeout. A large number may consume port resources.

5. Adjusting System Parameters for Excessive TIME_WAIT

If the system has many connections in TIME_WAIT state, you can optimize by adjusting Linux kernel network parameters.

Edit the configuration file:

vim /etc/sysctl.conf

Add or modify the following parameters at the end of the file:

net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1  # Caution: Use with care in NAT environments
net.ipv4.tcp_fin_timeout = 30

Apply the configuration:

sysctl -p

Parameter explanation:

  • net.ipv4.tcp_syncookies = 1: Enables SYN Cookies. When the SYN wait queue overflows, cookies are used to handle connections, offering some protection against SYN attacks.
  • net.ipv4.tcp_tw_reuse = 1: Allows TIME-WAIT sockets to be reused for new TCP connections.
  • net.ipv4.tcp_tw_recycle = 1: Enables fast recycling of TIME-WAIT sockets. (Warning: This can cause connection issues for clients behind NAT; newer kernels may deprecate or require careful evaluation of this option.)
  • net.ipv4.tcp_fin_timeout: Modifies the system's default TIME_WAIT timeout duration.

6. How to Properly Set Apache's Max Connections

When the number of online users increases and access slows down, but operations within a single connection remain smooth, it may be because Apache's maximum connection limit (MaxClients) is full, causing new visitors to queue.

6.1 Locate and Modify Configuration

First, confirm Apache's working mode (e.g., prefork):

apachectl -l

In the configuration file httpd.conf, ensure the MPM configuration is included:

Include conf/extra/httpd-mpm.conf

Then edit the corresponding MPM configuration block (e.g., for prefork).

6.2 Calculate a Suitable Value

The maximum number of connections is limited by server memory. First, estimate the average memory usage per httpd process:

ps aux | grep -v grep | awk '/httpd/{sum+=$6; n++}; END{print sum/n}'

If the result is 200KB (~200,000 bytes) and the server has 1.5GB of available memory, the theoretical maximum number of processes is approximately:

1.5 * 1024 * 1024 * 1024 / 200000 ≈ 8053

Considering other system overhead, a conservative value like 5000 can be set.

6.3 Configuration Example (prefork mode)

StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 5500        # Must be placed before MaxClients and be >= MaxClients
MaxClients 5000         # Maximum concurrent clients
MaxRequestsPerChild 100 # Recommended not to be 0, to prevent memory leaks

Note: The default maximum for MaxClients is 250. To exceed this, you must explicitly set ServerLimit, and ServerLimit must be placed before MaxClients.

6.4 Restart and Monitor

After restarting the Apache service, you can monitor connection count changes in real-time with:

watch -n 1 -d "pgrep httpd | wc -l"

or

watch -n 1 -d "ps aux | grep httpd | wc -l"

Observe if the connection count stabilizes near the set value, and adjust gradually based on actual traffic load and memory usage.

Post a Comment

Your email will not be published. Required fields are marked with *.