tags:

views:

619

answers:

3

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)

+3  A: 

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.

caf
A: 

Maybe have a look at Ncat as well:

"Ncat is the culmination of many key features from various Netcat incarnations such as Netcat 1.x, Netcat6, SOcat, Cryptcat, GNU Netcat, etc. Ncat has a host of new features such as "Connection Brokering", TCP/UDP Redirection, SOCKS4 client and server supprt, ability to "Chain" Ncat processes, HTTP CONNECT proxying (and proxy chaining), SSL connect/listen support, IP address/connection filtering, plus much more."

http://nmap-ncat.sourceforge.net

A: 

Try:

(cat somefile; sleep $timeout) | nc somehost 1234 | sed -e '{s/\x01.*//;T skip;q;:skip}'

This requires GNU sed.

How it works:

{
    s/\x01.*//; # search for \x01, if we find it, kill it and the rest of the line
    T skip;     # goto label skip if the last s/// failed
    q;          # quit, printing current pattern buffer
    :skip       # label skip
}

Note that this assumes there'll be a newline after \x01 - sed won't see it otherwise, as sed operates line-by-line.

bdonlan
This won't work because netcat will close the connection as soon as `cat` closes netcat's standard input.
caf
fixed, with a timeout even :)
bdonlan