How to count port traffic under Linux
- 2020-06-07 05:55:38
- OfStack
To monitor the exposed port traffic without modifying the source code, you can use Iptable, which comes with Linux, to add simple rules for port traffic statistics. However, it should be noted that the statistics are reset to zero when the server is restarted and the Iptable service is restarted.
Add ports that require statistics
1. Input monitoring
The following example is input traffic monitored on port 8080 --dport(short for destination port)
iptables -A INPUT -p tcp --dport 8080
2. Output monitoring
The following example is monitoring output traffic from port 8080 --sport(short for source port)
iptables -A OUTPUT -p tcp --sport 8080
View statistics
iptable -L -v -n -x
Sample results:
Port 8080 receives 2885 bytes of traffic and sends 8240 bytes
Chain INPUT (policy ACCEPT 202 packets, 25187 bytes)
pkts bytes target prot opt in out source destination
18 2885 tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 184 packets, 45774 bytes)
pkts bytes target prot opt in out source destination
12 8240 tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp spt:8080
Reset statistics
Note: Here are the statistics for resetting all ports
1. Reset all input ports
Iptable -Z INPUT
2. Reset all output ports
Iptable -Z OUTPUT
Remove statistics port
1. Remove the input port
iptables -D INPUT -p tcp --dport 8080
2. Remove the output port
iptables -D OUTPUT -p tcp --sport 8080