Android – How to passively monitor in Linux if a new TCP connection is being established?

How to passively monitor in Linux if a new TCP connection is being established?… here is a solution to the problem.

How to passively monitor in Linux if a new TCP connection is being established?

The simplest approach might be to write a loop to monitor /proc/net/tcp or /proc/net/tcp6. However, this is too inefficient because I need to be notified almost immediately. The closest thing I’ve seen is inotify, which provides callbacks for IO events for any file. The problem is that procfs is not a regular file system, and inotify doesn’t seem to support it (at least not /proc/net/tcp and /proc/net/tcp6).

Also, I don’t want the program to have root privileges to implement it.

EDIT: I removed the requirement for a userspace connection. Also, I would like to have a built-in kernel support such as inotify to enable this. In my case, manipulating iptables may even be too intrusive.

Does anyone know? Thank you!!

Solution

You can add logging rules to your on-premises iptables configuration, log a message whenever a new connection is initiated, and then enable non-root users to read the log file. This will allow you to (a) be notified of events immediately (you can use inotify to detect writes to files) and (b) detect that the process itself does not require root privileges.

Related Problems and Solutions