How can I close a netcat connection after a certain character is returned in the response?

SCdF picture SCdF · Aug 13, 2009 · Viewed 31.8k times · Source

We have a very simple tcp messaging script that cats some text to a server port which returns and displays a response.

The part of the script we care about looks something like this:

cat someFile | netcat somehost 1234

The response the server returns is 'complete' once we get a certain character code (specifically &001C) returned.

How can I close the connection when I receive this special character?

(Note: The server won't close the connection for me. While I currently just CTRL+C the script when I can tell it's done, I wish to be able to send many of these messages, one after the other.)

(Note: netcat -w x isn't good enough because I wish to push these messages through as fast as possible)

Answer

caf picture caf · Aug 13, 2009

Create a bash script called client.sh:

#!/bin/bash

cat someFile

while read FOO; do
        echo $FOO >&3
        if [[ $FOO =~ `printf ".*\x00\x1c.*"` ]]; then
                break
        fi
done

Then invoke netcat from your main script like so:

3>&1 nc -c ./client.sh somehost 1234

(You'll need bash version 3 for the regexp matching).

This assumes that the server is sending data in lines - if not you'll have to tweak client.sh so that it reads and echoes a character at a time.