network-programmingtcpudp

Monitor TCP/UDP port activity without binding


I'm trying to write a script/program to monitor for network connections to an existing process so that I can issue SIGSTOP/SIGCONT, docker (un)pause, etc, whenever there are no active connections to save cpu resources. I don't want to run a man-in-the-middle setup because I need the existing process to see the origin IP addresses and for performance. I'd prefer a method that doesn't require root/admin access but that's not essential. I'm primarily targeting Linux, but if I can write one implementation that works cross-platform that would be preferable. I don't need to know what is being communicated, I just want to set up a network inactivity timeout on a given port. I can use whatever language has the tools to get the job done. With all that in mind, how can I monitor for activity on a given TCP/UDP port?

EDIT: To be clear, this needs to also work for UDP, so periodically checking connection status isn't going to work. I need to know when a packet hits the server that is bound for the receiving process so that I can resume the process and start my own inactivity timer.


Solution

  • For now, I have found the least optimal solution in conntrack.

    sudo conntrack -E -p $PROTOCOL --dport $PORT

    By consuming the lines including [NEW] and [DESTROY], I can track the number of "active" connections to the server and pause the process when the connection number equals zero. This option is not great because it is linux-specific, requires root (or CAP_NET_ADMIN), and requires another conntrack process for every port, protocol, and IP version combination. The last point can probably be improved by using the conntrack library instead, but I'd still like to see other answers that don't have these requirements.