Kjetil's Information Center: A Blog About My Projects

Send and Receive files with Netcat

Here is a very simple way to send single files over the network, from one host to another. All you need is the netcat tool (also known as "nc" on the command line) and a couple of shell scripts. The transfer method is like FTP (over a straight TCP connection), but without the control channel.

Sender script:

#!/bin/sh
if [ -z "$1" ]; then
  echo "Usage: $0 <file to send>"
  exit 1
fi
nc $REMOTE_HOST 10001 -q 1 < "$1"
          


Receiver script:

#!/bin/sh
if [ -z "$1" ]; then
  echo "Usage: $0 <file to receive>"
  exit 1
fi
if [ -e "$1" ]; then
  echo "error: file exists."
  exit 1
else
  nc -p 10001 -l > "$1"
fi
          


In these examples, I am using a static host as the receiver ($REMOTE_HOST), so I don't need to specify it all the time. I have also decided on a static port number (10001) to use on both ends. The port number should probably be over 1024, so a normal user can create a listening socket on it. Also note that the receiver script always needs to be started before the sender script, if not, the connection will be refused.

Topic: Configuration, by Kjetil @ 29/11-2009, Article Link