How to count the port traffic under Linux
In the case of monitoring and statistics of port traffic exposed by the program without modifying the source code, we can use the Iptable included in Linux to add simple rules to make it play the role of port traffic statistics. However, it is important to note that the statistics will be reset to zero when the server is restarted and the Iptable service is restarted.
Add ports that need statistics
1. Input monitoring
The following example is to monitor incoming traffic with a target port of 8080-dport (abbreviation for destination port)
Iptables-An INPUT-p tcp-- dport 8080
2. Output monitoring
The following example is the output traffic that monitors the source port is 8080-sport (abbreviation for source port)
Iptables-An OUTPUT-p tcp-- sport 8080
View statistics
Iptable-L-v-n-x
Example result:
Port 8080 receives 2885 bytes of traffic and sends 8240 bytes of traffic
Chain INPUT (policy ACCEPT 202packets, 25187 bytes) pkts bytes target prot opt in out source destination 18 2885 tcp-- * * 0.0.0.0 policy ACCEPT 0 0.0.0.0 bytes 0 tcp dpt:8080Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 184packets 45774 bytes) pkts bytes target prot opt in out source destination 12 8240 tcp-- * 0.0.0.0 pkts bytes target prot opt in out source destination 0 0.0.0.0 Universe 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
The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.