I've made a small command to send a TCP message to an "IP-relay-unit" that can toggle the outputs.

printf "setstate,1:1,1\r" | nc ip.ip.ip.ip port

This actually works fine, sometimes. Since the printf worked on both linux and mac, I thought it had to do something with netcat. I noted that using -v on netcat improved the amount of times it went right, but this seems like a very dull workaround.

I later found the nc -i option, to add a timeout of 1 sec, which hasn't yet caused an error (on both Linux or OSX), though it does decrease the execution time and still isn't a 100% clean fix.

The man page actually shows that piping into the nc command can be done, it doesn't mention any possible race conditions.

Is this expected behaviour? And is there a clean way of fixing this? (like "--only-send-when-connection-is-complete") or can I actually check if it's a race condition?

  • many IoT small devices will be slow to connect and accept data, especially if tried several times a second. Your printf is not at fault. You might try nc's -w option to change the timeout to connect. – meuh Mar 30 '17 at 17:21
  • @meuh Hmm, good point actually! I was worried this was a "bug" in Unix, that it would send before connecting. But some devices may indeed not directly accept data after connecting. So using a 1sec delay would work always (if the device will accept it then) and it will not be bound to the speed of the actual connecting. – Paul Mar 30 '17 at 18:01
  • Long story short, it will get send after connecting. But some devices do not support that? 1sec delay is a valid fix. Do you want me to accept the current answer to mark it fixed, or would you prefer creating an answer out of your comment? – Paul Mar 30 '17 at 18:04
  • It might be useful to others for you to create an answer of what works for you. Normally, writing to a network device immediately after connecting should work. Your device is just a little slow and needs special care for some reason. – meuh Mar 30 '17 at 18:11

You can check if there is an active connection with:

nc -v <HOST> <PORT> </dev/null; echo $?

If the above command, returns you the value 0, then the connection is successful and you can printf your message, otherwise (value is 1), then you know that your connection is refused or timed-out etc.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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