Calculate the traffic for specific port forwarded in the Linux

416 Views Asked by At

I have a server running Linux : server A I want the traffic on server A to be redirected to remote server b Actually do the same as the forward port I used the following command for the forward port.

sysctl net.ipv4.ip_forward = 1
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 150 -j DNAT - to-destination des_ip:dest_port
iptables -t nat -A POSTROUTING -j MASQUERADE

The forward port did well and i could connect to server B through server B. Now I want to know how much traffic is used on port 150 on server A? If Server A is not a router, I can easily set a limit with the following commands and calculate the traffic consumed on Server A.

sudo iptables -A INPUT -p tcp --dport 150 -j DROP
sudo iptables -A INPUT -p tcp --dport 150 -m quota --quota 100000000 -j ACCEPT

But because server A is a router, these commands do not work Is there any other command line that I can use to calculate the consumed traffic of port 150 on server A(server A is a router)? I want to collect the usage data of each port using Python and store it in the database.

1

There are 1 best solutions below

0
Amin On

In this question, I wanted to redirect port 150, which is the source port, to the destination port.

After research about PREROUTING and INPUT chain in iptables, this is what I realized:

INPUT chain is after PREROUTING chain. According to this schematic.

Ports are translated to the destination port, in PREROUTING chain by NAT, therefore In INPUT chain there is no traffic with the source port and all traffic translated to destination port.

I can see network usage on destination port in INPUT chain, but I can not see the network usage on source port in INPUT chain.

Because all packet headers translated to destination port.

So it's true that quota for source port does not start count in any of the chains.

Even if I create the following rules in FORWARD chain:

sudo iptables -A FORWARD -p tcp --dport 150 -j DROP
sudo iptables -A FORWARD -p tcp --dport 150 -m quota --quota 100000000 -j ACCEPT

Again, we will not see any change in quota Because the FORWARD chain is after the PREROUTING chain.