mr. Gauss
mr. Gauss

Reputation: 661

Is there a way to programatically check for used ports without looping?

I'm familiar with couple of methods to check for used ports on Android.

  1. Loop over all possible ports, try creating a socket on each port, if socket creation fails port is used.
  2. Use netstat command from shell which will list all open connections and used ports can be parsed from there.
  3. Use cat /proc/net/tcp command from shell which is similar as netstat command.

Problem with 1st option is that looping over all possible ports is taking too much time, it's not efficient enough if I want to make sure that I'm getting all open ports.

Problem with 2nd and 3rd option is that (on non-rooted device) although shell command can be executed in shell (adb shell) and output is clearly seen, while trying to execute command from Java code in Android application, command output is empty string for cat /proc/net/tcp and only header is outputted from netstat command. I'm guessing that the problem are application permissions which are insufficient to run above commands.

Is there any other way of checking for used ports or am I doing something wrong by using commands from option 2 or 3?

EDIT: To clarify, while using any command that should list connection info from adb shell this will work fine. However, if I'm trying to invoke any of the commands (same syntax as in adb shell) from my application's Java code, output of the command is empty string.

To get the process I tried using:

  1. Runtime.getRuntime().exec(command);

  2. new ProcessBuilder().command("sh", "-c", command).start();

E.g. output of netstat command (with any arguments) is as following:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address           Foreign Address         State      Active UNIX domain sockets (only servers) Proto RefCnt Flags   Type       State       I-Node Path

Upvotes: 0

Views: 1372

Answers (1)

Raman Sailopal
Raman Sailopal

Reputation: 12887

How about:

netstat -ln | awk '/^tcp/ { split($4,arr,":");prts[arr[2]]="" } END { for (i in prts) { print i } }'

Take the netstat output and then using awk, concentrate on all lines beginning with tcp. Then split the 4th delimited field into a array called arr based on ":" as the delimiter. Put the second index of the array (port number) in another array prts as the index. At the end, loop through the prts array and print the indexes (ports)

Upvotes: 0

Related Questions