Imagine in a Linux-based router (a Debian distro) you have many NICs. How to print out number of open connections for a given NIC? (workarounds are acceptable answers)
-
What kind of a router? They aren't all identical. – u1686_grawity Jan 25 '21 at 19:03
-
@user1686 Debian environment based – J. Doe Jan 25 '21 at 19:59
3 Answers
Option 1
netstat | awk '$4 ~ /xxx.xxx.xxx.xxx/ { ++count } END { print count }'
Where xxx.xxx.xxx.xxx is the NIC's IP address.
netstatwill find all open connectionsawkmatches the IP address of the NIC$4tellsawkthat we'll be looking at the 4th column{ ++count } END { print count }tellsawkto count up for each time it finds a match. When it's done, print out the final count.
Option 2
netstat | grep xxx.xxx.xxx.xxx -c
Where xxx.xxx.xxx.xxx is the NIC's IP address.
netstatwill find all open connectionsgrepmatches the IP address of the NIC-casksgrepto count the number of matches, rather than print them out.
Option 1 has the benefit of only matching on the local address field rather than anywhere. Option 2 might double count if there are open connections where the remote address points to the localhost.
- 321
- 2
- 13
-
This only shows connections made or received by the router itself (i.e. it shows sockets held by local processes) – it doesn't show those that go *through* the router. – u1686_grawity Jan 25 '21 at 22:31
You can't. Basic IP routers just statelessly forward datagrams, only looking at the IP layer. They wouldn't know anything about any connections for which they are not the endpoint.
An SPI firewall or a NAT gateway is a different story.
- 101,729
- 17
- 175
- 229
The router doesn't track connections – you need to ask the firewall.
The Linux firewall supports stateful "connection" tracking, but it isn't necessarily active by default. If you have any of these:
- an iptables rule which uses
-m stateor-m conntrack, - or an nftables rule which uses
ct state, - or any rules in the iptables/nftables NAT tables (e.g. the nat/prerouting chain),
then the firewall's conntrack system is active and you can look at its "state table" using:
conntrack -L
However, because this is done by the firewall (not the router), the states have no relationship with any particular interface – they only care about L3/L4 addressing.
- 426,297
- 64
- 894
- 966