Search code examples
linuxbashshellexit-codenetcat

GNU netcat exit code always 1?


I'm trying to use GNU variant of netcat in script but it always returns exit code 1 even if everything is fine. Here's my case step by step:

  1. run nc -l 127.0.0.1 -p 7000
  2. run nc 127.0.0.1 7000
  3. press ctrl+c on client nc
  4. server nc always returns 1

It makes me unable to detect socket bind error in bash script. Precisely it's GNU netcat from Arch linux. BSD netcat for Arch doesn't fail on socket bind error when address is in use so it's not much better either...


Solution

  • After looking at the GNU Netcat source code, I have a bad news for you...

    int c, glob_ret = EXIT_FAILURE;
    

    The variable glob_ret is set to EXIT_FAILURE (1) and only changes in port scan mode or tunnel mode. The variable isn't set in listen mode, so the program will always exit with a 1 code.

    You can take a look at the netcat.c source file here : https://pastebin.com/fh66BPgg (function main)