Android: programmatically determine list of apps that have a TCP connection open

血红的双手。 提交于 2019-11-29 05:11:34
eolwral

If you read source code for 'netstat', it actually reads data from /proc/net/tcp which holds a dump of the TCP socket table, the data will like below.

sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
 0: 0100007F:13AD 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 517 1 cbf19b40 300 0 0 2 -1

you will discover each connection has a uid, because Android OS run each application with a user account that means own a unique uid, it will help to map every connection to a single process.

I hope this information will help.

On several android 4.x I've seen genuine IPv4 connections appear with IPv4-mapped-IPv6 addresses in /proc/net/tcp6 instead of plain v4, like this:

    sl  local_address                         remote_address                        st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
   0: 0000000000000000FFFF00000100007F:99FC 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 10071        0 32037 1 00000000 300 0 0 2 -1
   1: 0000000000000000FFFF00005EE9A8C0:9BB0 0000000000000000FFFF000007E6AB45:01BB 08 00000000:00000001 00:00000000 00000000 10071        0 32270 1 00000000 22 4 6 6 -1

So it seems you should check udp6/tcp6 as well.

I think there are two possible reasons.

  1. It is due to permission problems, because some Android distribution version has more restrict permission settings, you should try to read data from /proc/%pid%/net/tcp (%pid% replace by PID for your app).

  2. the system is working on IPv6, you need to check "/proc/%pid%/net/tcp6" instead of "/proc/%pid%/net/tcp", its ip will need to convert from IPv6 to IPv4.

Use busybox command to get process info

busybox netstat -tp
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!