Bash snippet to see if something is listening on a port?
7,687
Solution 1
lsof -i :14881
Solution 2
Maybe netstat would be better because the port might not be listening on localhost or it might be blocked by iptables:
netstat -ln | grep :14881
echo $?
Grep will exit with 1 if there is no match. If you want just tcp and/or udp , add the -u or -t switches to netstat.
Solution 3
If you are root:
netstat -lnp | grep ':14881 '
Solution 4
I use this in bash for exiting when no-one listening to this port.
$port="14881"
if [[ $(netstat -ltn | grep ":${port} " | wc -l) -eq "0" ]] ; then echo "Port $port not listened to" && exit 1; fi
- Using bash double brackets and comparing against wc for easy reading..
Related videos on Youtube
Author by
Araejay
Updated on September 17, 2022Comments
-
Araejay over 1 year
I want to see if something is listening on a port on localhost. I was going to use
nc
and check the exit code.Something like this:
echo "" | nc localhost 14881 echo $?
Any other suggestions?
-
Admin almost 15 yearsthere are many reasons why you'd want to do this, but I'm curious as to your reason here... it may be possible you can avoid the port-check altogether. Do you have a 'slow start' scenario? where the application daemonizes but takes another minute or two before it actually opens up a listener? or are you just trying to avoid a lengthy timeout situation? or are you unable to handle the case where you get connection refused?
-
Admin about 7 yearswith nc correct way will be nc -z "$host" "$port", in bash though the proper way would be echo '123' > /dev/tcp/localhost/port" and if there is nothing listens it will says: "bash: connect: Connection refused"
-
-
Dan Carley almost 15 yearsJust to be clear: it will still work if you aren't root but you won't benefit from seeing the process name bound to it.
-
Dan Carley almost 15 yearsWoah, lay off the pipes. You can replace the first two egreps with
-lt
instead of-ao
and a normal grep on the port. Or, if you wished, perform everything as a single egrep. -
msanford almost 15 yearsThis one provides lots of great data.
-
Kyle Brandt almost 15 yearsOn my desktop system this one requires root.
-
Justin over 7 years
lsof -i :14881 | grep ":14881"
then you can useecho $?