14

Is it possible to listen to a port continuously?

I listen for incoming tcp notifications with following command

sudo nc -l -p 999

But as soon as notification arrives I have to restart listen with same command. Is it possible to listen to port without having to restart command when notifications arrives until user decides to abort listen?

4
  • Exactly, so whenever a notification arrives it should be printed in terminal without the need to manually restart command.
    – S4M11R
    Commented Mar 7, 2016 at 10:11
  • 1
    Does this work: while true; do nc -l -p 999; done
    – dreamlax
    Commented Mar 7, 2016 at 10:13
  • I get a syntax error sudo while true; do nc -l -p 999; done bash: syntax error near unexpected token `do'
    – S4M11R
    Commented Mar 7, 2016 at 10:15
  • If you want to use it with sudo, you have to use sudo sh -c 'while true; do nc -l -p 999; done'
    – dreamlax
    Commented Mar 7, 2016 at 10:20

2 Answers 2

42

Sorta outdated question, but came up first on my Google search.

In order for netcat not to shutdown as soon as the first connection is received, you can add the -k option.

From the man:

-k Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.

Src: https://superuser.com/a/708133/410908

1
  • 1
    On Debian -k is present only in nc.openbsd Commented Nov 21, 2023 at 10:56
6

Solved with a simple bash script

#!/bin/bash

#Make Sure Script Is Ran As Root
if [ $(id -u) != 0 ]; then
    echo; echo -e "\e[1;31mScript must be run as sudo. Please Type \"sudo\" To Run As Root \e[0m"; echo    
exit 1
fi

echo "Enter port to listen"
read portL

while true;
do
    nc -l -p $portL
done
exit 0

Thanks dreamlax for the tip!

4
  • 1
    I would avoid putting sudo in the loop like that ... unless it is configured not to prompt for a password, it may cause issues if nothing is received for 15 minutes (or whatever the sudo timeout is configured on your system) and sudo is run again.
    – dreamlax
    Commented Mar 7, 2016 at 10:21
  • Better to remove sudo from script then run script as sudo? Ex: sudo tcpListen.sh
    – S4M11R
    Commented Mar 7, 2016 at 10:26
  • Yeah, that would be better I think!
    – dreamlax
    Commented Mar 7, 2016 at 11:24
  • I would emphasize: just run this as the root user and have it check if real UID is 0. Alternatively, run it as a user with sudo configured as NOPASSWD ALL. Two choices. You won't get far automating things if there's a prompt to deal with. (Don't try what some recommend, trying to "answer" the password prompt, ugh) Commented Sep 13, 2018 at 14:57

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