0

I don't understand how to properly setup a data transmission between two host with unstable ethernet connection.

This is my /simple/bash/script.sh

#!/bin/bash


while [ true ]; do
    cat /dev/virtual  | nc -v 192.168.1.1 5005 || echo "nc failed" && exit   
    sleep 5s
done

exit

If I manually start it and on the destination netcat isn't running it would say:

5005 (tcp) failed: Connection refused

But it would not exit.

I need it the other way:

  1. check netcat connection is ok.
  2. then pipe cat /dev/virtual.

Is there a way to catch the netcat status and then if it is failed: connection refused restart the main bash script?

Hauke Laging
  • 88,146
  • 18
  • 125
  • 174
user340971
  • 407
  • 1
  • 4
  • 13

1 Answers1

0

This should work:

#!/bin/bash

if ! nc -z 192.168.1.1 5005 ; then
    sleep 1 && "$0" & exit;
fi

nc -v 192.168.56.203 5005 < /dev/virtual

Explanation:

  • nc -z will check if someone is listening on the other side
  • if no one is listening, the program will sleep for 1 sec (obviously you can change this) and then it will start another instance of itself and exit
  • if someone is listening, then the program will send /dev/virtual
Francesco
  • 808
  • 7
  • 24
  • Thank you, I've tried with: if ! nc -z $IPADDRESS 5005 ; then echo "Not avilable" && sleep 1 && "$0" ; fi But connection on the other side get closed after the execution: " nc -i 1 -l -v -p 5005 Listening on [0.0.0.0] (family 0, port 5005) Connection from 10.11.10.11 33908 received!" – user340971 Jun 09 '20 at 06:40
  • @user340971 if you're not running on Debian, you can use the `-k` option of netcat. Check those answers: [how-can-i-keep-netcat-connection-open](https://unix.stackexchange.com/questions/423407/how-can-i-keep-netcat-connection-open), [nc-exits-immediately-on-connection](https://serverfault.com/questions/754705/nc-exits-immediately-on-connection-when-run-as-an-upstart-job). If you're running on Debian, check this answer: [netcat-keep-listening-for-connection-in-debian](https://superuser.com/questions/1008348/netcat-keep-listening-for-connection-in-debian) – Francesco Jun 09 '20 at 07:46