Netcat TCP Programming with Bash
Asked Answered
L

1

7

I'm attempting to do some basic TCP client communication by using strictly bash scripting. I have netcat at my disposal and so I've written this loop so far:

nc 10.0.0.104 4646 | while read line
do
   if [ "$line" == '{"cmd": 1}' ]
   then
      # Send text back to the TCP server
      echo '{"error": 0}'
   fi
done

The script can successfully connect to the server application I'm using but I'm having difficulties figuring out how to send text back to the netcat process.

Lavernlaverna answered 21/12, 2014 at 15:31 Comment(0)
P
6

With Bash≥4 you can use coproc:

#!/bin/bash

coproc nc { nc 10.0.0.104 4646; }

while [[ $nc_PID ]] && IFS= read -r -u${nc[0]} line; do
    case $line in
        ('{"cmd": 1}')
            printf >&${nc[1]} '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

This avoids using temporary fifos. Without coproc, I guess the only option left is to use fifos explicitly. Here's an example:

#!/bin/bash

mkfifo fifo_in

while IFS= read -r line; do
    case $line in
        ('{"cmd": 1}')
            printf '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done < <(nc 10.0.0.104 4646 < fifo_in) > fifo_in

For this, you'll have to manage the creation and deletion of the fifo: you'll need to create a temporary directory with mktemp, in there create the fifo, then trap your script so that on exit everything is cleaned.


/dev/tcp

If your Bash has been compiled with net redirections support, you can get rid of nc and of the fifos and coprocesses altogether:

#!/bin/bash

# open TCP connection, available on file descriptor 3
exec 3<> /dev/tcp/10.0.0.104/4646 || exit

while IFS= read -r -u3 line; do
    case $line in
        ('{"cmd": 1}')
            printf >&3 '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

This is very likely the sweetest solution!

Pantomime answered 21/12, 2014 at 16:42 Comment(1)
good stuff. In case O.P. can't use bash 4, these features have been in ksh for several years. But that depends on what version of ksh is available too, but worth testing. O.P. may avoid having to install something new in a production environment. Good luck to all.Dionne

© 2022 - 2024 — McMap. All rights reserved.