I'm looking to bind to a port for SSH tunnelling via a simple shell script (likely: BASH), and I'd like a more ... "sane" manner of testing whether or not the port is already bound to another process, and I'd rather not like to grok (read: grep) the output of netstat.

Is there some command or utility that makes doing this sane? I either have terrible google-fu and a terrible vocabulary, or most people don't try to iterate over ports programmatically via a shell, but instead via a programming language.

link|improve this question

3  
A bit less heavy than netstat, though still same concept: fuser <port>/tcp. – Max Alginin Nov 5 '09 at 1:50
feedback

2 Answers

up vote 5 down vote accepted

you could use lsof:

*-i i select by IPv[46] address: [46][proto][@host|addr][:svc_list|port_list]*

lsof -i 4TCP@0.0.0.0:80
link|improve this answer
1  
You were a few seconds ahead of me :) – Alex Nov 5 '09 at 2:59
1  
While lsof works, looping through every process and it's open ports is slow. netstat -tan will give you the list of open ports. – David Nov 5 '09 at 3:42
feedback

Another option would be lsof. You can do something like:

lsof -i tcp:<port> -s tcp:listen
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.