How to Monitor Traffic on a Specific Port with iptables

To monitor and collect traffic statistics for the ports exposed by a program without modifying the source code, you can use the built-in Iptable in Linux to add simple rules so that it can be used for port traffic statistics. However, note that the statistics will be reset to zero when the server restarts or the Iptable service restarts.

Add the port to be counted

1. Monitor inbound traffic

The example below monitors inbound traffic for target port 8080
–dport (short for destination port)

iptables -A INPUT -p tcp --dport 8080

2. Monitor outbound traffic

The example below monitors outbound traffic with source port 8080 –sport(short for source
port)

iptables -A OUTPUT -p tcp --sport 8080

View statistics

iptable -L -v -n -x

Example output:

The traffic received on port 8080 is 2885 bytes, and the traffic sent is 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: this resets the statistics for all ports

1. Reset all inbound ports

Iptable -Z INPUT

2. Reset all outbound ports

Iptable -Z OUTPUT

Remove counted ports

1. Remove inbound port

iptables -D INPUT -p tcp --dport 8080

2. Remove outbound port

iptables -D OUTPUT -p tcp --sport 8080

Leave a Comment

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

中文 EN
🚀

RedGate VPN

免费节点太挤太慢?
升级高速稳定专线

立即体验 →

告别卡顿

RedGate VPN
全球高速节点

免费下载 →
Scroll to Top