Saturday, March 20, 2010

Using NetCat (nc) running in the background

Short version: use nc -dl portNumber instead of just -l

Netcat is a nice little tool that is very useful in all kinds of networking problems. Basically it listens on a port and it sends to ports via TCP/IP. Using the piping mechanism of Linux, one can send anything, from files compressed on the fly in the network stream to telnet sessions and back doors.

Today I was trying to copy a few files from a computer to another, therefore I did something like this:
tar -c -C /source/folder file1 file2 file3 | nc theOtherComputer portNumber
on the second computer I did this:
nc -l portNumber | tar -x /destination/folder

And it worked perfectly. I made all kinds of cool stuff in the bash scripts and then, wanting to execute the "server" in the background I did:
serverApp &

From then on, nothing worked. The sender would report success, the received file would always be truncated. After trying all kinds of things, I stumbled upon the -d switch of the nc tool. The man page says: -d' Do not attempt to read from stdin.. It appears the application is trying to keep a reference to the input of the starting environment. It makes no sense for a listening scenario, but it does it anyway. Failing to find one (since it is runnning in the background), it just exits earlier than expected.

So, whenever you want to use NetCat listening in the background, don't forget to use the -d switch.


Anonymous said...

Thanks for this :)

Anonymous said...

Thanks! Although without -d, nc doesn't exit early, only after the connection closes. But then process stays in stopped state and keeps the port open.

Anonymous said...

Thank you so much. This one saved my day!

Anonymous said...

Thanks. I was hammering away on this and your post set me straight.

Anonymous said...

Still true as of 1.84-22 on Red Hat 6.4

Anonymous said...

Thanks a lot, saved another man's life!