How to modify input stream of netcat?

5.3k views Asked by At

I'm creating a TCP/IP interface to a serial device on a redhat linux machine. netcat in a bash script was used to accomplish this with out to much trouble.

nc -l $PORT < $TTYDEVICE > $TTYDEVICE

The problem is that the serial device uses carriage returns('\r') for line ends in its responses. I want to translate this to ("\r\n") so windows machines telneting in can view the response without any trouble. I'm trying to figure out how to go about this with a simple bash solution. I also have access to stty to configure the serial device, but there is no "\r" to "\r\n" translate on the input side(from what I can tell).

I did try to use tr on the input side of netcat, but it didn't work.

#cat $TTYDEVICE | tr '\r' '\r\n' | nc -l $PORT > $TTYDEVICE

Any ideas?

3

There are 3 answers

4
William Pursell On BEST ANSWER

This is overly difficult with standard tools, but pretty easy in perl (although perl is pretty much a standard tool these days):

perl -pe 's/\r/\r\n/g'

The version above will likely read the entire input into memory before doing any processing (it will read until it finds '\n', which will be the entire input if the input does not contain '\n'), so you might prefer:

perl -015 -pe '$\="\n"'
1
jørgensen On

Your problem is that the client that connects to $PORT probably does not have a clue that it is working with a tty on the other side, so you will experience issues with tty-specific "features", such as ^C/^D/etc. and CRLF.

That is why

socat tcp-listen:1234 - | hexdump -C
telnet localhost 1234
[enter text]

will show CRLFs, while

ssh -t localhost "hexdump -C"
[enter text]

yields pure LFs. Subsequently, you would e.g. need

ssh -t whateverhost "screen $TTYDEVICE"

tl;dr: netcat won't do it.

1
stsquad On

There are a number of versions of netcat (GNU and BSD) but you might want to try:

 -C      Send CRLF as line-ending