Get process id based on port number

956 views
Skip to first unread message

ezmora

unread,
Dec 2, 2010, 9:04:54 AM12/2/10
to android-ndk
I'd like to write a method that receives as a parameter a port
number,
and returns the process id that listens on this port.
Any ideas?

Eyal

Onur Cinar

unread,
Dec 2, 2010, 1:23:49 PM12/2/10
to andro...@googlegroups.com

Hi Eyal,

There can be an easier solution, but as far as I recall, It will be a multiple step process.

You will first read the "/proc/net/tcp" (and/or) "/proc/net/udp".

They will look like something like this:

sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode                                                    
1: 0100007F:410A 00000000:0000 0A 00000000:00000000 00:00000000 00000000 10001        0 3235 1 c7c54940 300 0 0 2 -1

The important column here is the "local_address", where you can parse the port number (in hex), the "uid" which is the user id for the process, and the "inode".

On Linux we could use this inode to check the /proc/<pid>/fd directory, to quickly find the process id, but on Android, we don't have permission to go into the /proc/<pid> directory for other processes,  so we can ignore the inode for now.

With the "uid" (10001) only, we can still do a guess.   First we need to get the actual username for this uid.  In order to do so, you need something like this:

#include <sys/types.h>
#include <pwd.h>

strcut passwd* pw = getpwuid(uid);

pw->pw_name   is the username after the call.

On my system, the uid 10001 turned out to be app_1.

Now we can use the  popen("/system/bin/ps", "r") to open op the process list.

The columns are as:

USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
app_1     602   68    148808 18592 ffffffff 00000000 S com.htc.android.footprints

With sscanf, you need to parse each line, and then you can compare the first column with the username that we are looking for.

If there is a match, the last column is the name of the actual package, and the PID column will have the process id.

For system applications, you can see multiple matches, but for regular Android applications there should be a single match.

I hope this helps.

Best regards,

-onur





--
You received this message because you are subscribed to the Google Groups "android-ndk" group.
To post to this group, send email to andro...@googlegroups.com.
To unsubscribe from this group, send email to android-ndk...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/android-ndk?hl=en.

---
www.zdo.com

eyal zmora

unread,
Dec 4, 2010, 2:07:34 PM12/4/10
to andro...@googlegroups.com
Hi Onur
 
Responsive & helpful as always :-)
I haven't tried your solution yet, but it sounds good.
 
Thanks,
Eyal

2010/12/2 Onur Cinar <onur....@gmail.com>
Reply all
Reply to author
Forward
0 new messages