5

I'm trying to identify what application is running on port 56474 without having root access. I know the application was started by me.

Example:

netstat -tunap

tcp        0      0 0.0.0.0:56474           0.0.0.0:*               LISTEN      -               

I've tried using /proc/pid scripts to walk all using grep on ls -l /proc/pid/fd results. Here is my attempt. NOTE: Not sure if I was heading the right direction

for I in `find /proc/*/fd -exec ls -l {} \; 2>/dev/null | awk -F"->|:" '/socket/ {print $4}' | sort -u | sed -e 's/\[//g' -e 's/\]//g'`; do grep $I /proc/*/net/tcp; done

I had no success. Not sure if there is a way. Thanks.

skibur
  • 95
  • 2
  • 8

3 Answers3

10

NOTE: Added another answers as lsof was not satisfactory.

This should work:

#! /bin/bash
port=56474
hex_port=$(echo "obase=16; $port" | bc )

inode=$(cat /proc/net/tcp | grep ":$hex_port" | awk '{print $10}')

for i in $(ps axo pid); do
        ls -l /proc/$i/fd 2> /dev/null | grep -q ":\[$inode\]" &&  echo $i
done 

Explanation:

Once we have the port number converted to Hexadecimal, we can get the inode number from /proc/net/tcp (10th field), then we loop through /proc/pids/fd and find a symlink pointing to the inode.

Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51
  • Nice! It works! I ran it it give me a the pid of the application's name. Thanks for your help. – skibur Jun 20 '14 at 00:40
  • This doesn't work on all systems without root access, because sometimes you're not allowed to access `/proc//fd`. PS Sorry, I've missed the "I know the application was started by me" sentence, so the poster has access to his own `/proc//fd`. – t0r0X Mar 23 '16 at 12:19
  • 2
    The usual [useless use of `cat`](http://www.iki.fi/era/unix/award.html) fix: `awk ":$hex_port { print \$10 }" /proc/net/tcp` – tripleee Jan 20 '17 at 09:21
0

If you're sure the application was started by you then you can use lsof:

/usr/sbin/lsof -nP | grep :56474 | awk '{print $2}'

Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51
0

Another technique to resolve pids and ports of all running apps without root:

1.) Get the pids of running apps. Either use the ActivityManager or parse a ps console output.

2.) iterate through /proc/$pid/net/status files and get the matching uid for a pid.

    cat /proc/*pid*/net/status | grep Uid:

3.) Call and parse the output of tcp, tcp6,udp, udp6 files to match ports and uids:

    cat /proc/net/tcp 
    ...

4.) match the uids of both matchings, get a port-to-pid map without su access.

Cheers,

goethe

Goethe
  • 1
  • 1