Find out which process is holding which socket open

Contributor Icon Contributed by bofh468 Date Icon November 14, 2003  
Tag Icon Tagged: UNIX

You’ve run netstat -an. You see that port TCP/65237 is listening. What program is actually running and holding that port open? Here’s how to find out.


Sometimes you notice odd ports open and listening on your machine. In this day and age, that’s often a bad thing. But what do you kill to close off that port? Is that port supposed to be open (ie, something legitimately running).

You’ve probably heard of lsof. List Open Files. You usually use it to find out what files are open on a given mount point. Well, you can also use it to find out what open sockets your machine has:

# lsof -nl | egrep "TCP|UDP"

wish 30766 500 4u IPv4 1051584 TCP *:65237 (LISTEN)
wish 30766 500 6u IPv4 1051588 TCP *:63251 (LISTEN)
#

That shows that my workstation, while typing this message, has wish running at PID 30766. It’s listening on two ports: TCP/65237 and TCP/63251.

You can then run ps to determine what that process really is (no worries… it’s aMSN on my workstation) and decide if you really want to kill it off.

If you’re running Solaris, you won’t be graced with lsof unless you install it from source or via SunFreeWare. It does come installed by default on many Linux distributions.

Previous recipe | Next recipe |
 
  • Anonymous
    Actually, you can skip a whole step there... if you add the '-p' argument to netstat, it includes the PID of the process in question!

    So instead of netstat -an, try netstat -anp.
  • Anonymous
    netstat -anp works on linux, but not Solaris :-(
  • Guest
    Just use /usr/proc/bin/pfiles <pid> bit of a pain to do it in reverse (i.e. speicfy pid to get the port) but a simple script can rip thru it for you....

    echo "which port?> "
    read port

    for pid in `ps -ef -o pid | tail +2`
    do
    foundport=`/usr/proc/bin/pfiles $pid 2>&1 | grep "sockname:" | grep "por
    t: $port$"`
    if [ "$foundport" != "" ]
    then
    echo "proc: $pid, $foundport"
    fi
    done
blog comments powered by Disqus