Android 10 - netstat execution not working properly

2.8k Views Asked by At

I'm trying to run a shell command in my Android app in order to check if a give tcp port is opened or not:

Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn | grep :8080"))

Running this command in Android version < 10, works fine. It will do a full scan and return the entry if there is the given port used.

But in Android 10, it is not working anymore. The process exec will return:

Process[pid=9534 ,hasExited=true, exitcode=1]

When reading the inputStream of the process it is always null, while executing netstat -tulpn | grep :8080 from terminal will return an entry, as expected.

Running

Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn"))

alone, and parsing the output, will only show:

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program Name

and no other data at all.

I only have this problem in Android 10, because for older versions it is working.

Has anything changed in Android 10 regarding to shell commands? It is necessary for me to run this command. Any help would be appreciated...

2

There are 2 best solutions below

3
On

My goal was to check if a given tcp port was in use or not. I made this method that did the job that I was looking for:

private fun isPortUsed(port: Int): Boolean {
    return try {
      // Try to open socket at the given port
      val socket = ServerSocket(port)
      // Release port
      socket.close()
      false
    } catch (ex: BindException) {
        // Port is already in use
        true
    } catch (ex: Exception) {
        // Other reason for failing
        false
    }
}
3
On

This is most likely because of privacy protection improved in Android 10.

Look here: https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem