Thursday, July 19, 2007

Simple Newbie's Guide to netstat

I've been using Linux for 8 or 9 years now and I have always heard that, in order to find out what program or process is using a given open port on your computer you should use the program "netstat".

Whenever I've asked just exactly how one uses netstat, I've been told "netstat -a".

Now, for those that think that's the right answer, please go try "netstat -a" and see just exactly what it tells you. Can you use that information to find out what program or process is holding that mysterious port open? Uh-huh. I thought the same thing the first time I tried it.

I have essentially ignored netstat and worked around it, because it's man page is one of the better examples of a wonderfully esoteric but not-too-helpful man page: it lists paragraph after paragraph of command options, leaving the average newbie's mind in a rather confused state.

Today I took the time to read the long-winded man page and found that netstat really can tell me what I want to know:

-v Gives "verbose info" (of course), though I didn't find this very handy.
-l Shows only listening sockets. This is not a default option, and you really want to see the information -l has to show you.
-e Display additional information.
-p Show the PID and name of the program to which each socket belongs.

-p is the real winner here: it shows you the process number of the program that's using this port, and the name of the program. This will enable you to find the process in ps, and/or kill that process.

Since "netstat -a" puts out a whole lot of info, I found that starting with "netstat -lt" and "netstat -lu" is a great first or second step for finding your open ports (the other one being port scanning, which you really should do anyway). Once you find a port you want to close, you can run "netstat -aevp" and grep for the port number (or port name as found in /etc/services) you are interested in to find the program's PID and name (netstat -aevp | grep 59849).

Give it a try:

netstat -lt
netstat -lte
netstat -ltv
netstat -ltp
netstat -aevp
netstat -aevp | grep sunrpc
netstat -aevp | grep domain

1 comment:

HaleyRose said...

you can also use netstat -ao, it gives you the listening ports and such, and the PID so you can end them in the processes section of the task manager if you need to based on this.