I need to use
nc in a weird way, where I want the server to first send a file, and then receive a file, and this repeats. I would like to have every instance of the server server close after some seconds. How can I do this in a script? I already have a client that can interact with the server.
I need to use
Some netcat implementations have a timeout option. For the one on my system, it is
$ nc -l -p 2000 -w 5
will listen on port 2000 and exit in 5 seconds unless a connection is attempted on that port.
Because of the documentation :
The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag
socat, no one can set timeout for server mode.
As far as I know, only
busybox nc can follow
-w option in server mode.
So you have to download busybox which compiled with
CONFIG_NC_SERVER=y option, or compile it by your self.
So that you can
$busybox nc -w 10 -l -p 9999
But my system's busybox didn't compile with
CONFIG_NC_SERVER=y option, and I don't want compile it. So I use this solution:
portnum=9999 (sleep 10 ;echo "T" | nc -w 1 127.0.0.1 $portnum) | nc -N -l -p $portnum
After 10 seconds, send "T" to localhost:9999
The full code is
#!/bin/sh portnum=9999 testmsg="Hello_World" if [ "$( (sleep 10 ;echo "T" | nc -w 1 127.0.0.1 $portnum) | nc -N -l -p $portnum )" = $testmsg ]; then echo "Test pass" else echo "Test not pass" fi
If server received
Hello_World in 10 seconds, it will print
Test pass. Otherwise print
Test not pass
You can try open another console, and type
echo "Hello_World" | nc -w 1 127.0.0.1 9999
to test it.