How to make an Echo server with Bash?
Asked Answered
S

5

58

How to write a echo server bash script using tools like nc, echo, xargs, etc capable of simultaneously processing requests from multiple clients each with durable connection?

The best that I've came up so far is

nc -l -p 2000 -c 'xargs -n1 echo'

but it only allows a single connection.

Swanhildas answered 4/12, 2011 at 14:9 Comment(1)
Ubuntu 12.04's nc has no -c option =( (netcat-openbsd package).Bordelaise
P
56

If you use ncat instead of nc your command line works fine with multiple connections but (as you pointed out) without -p.

ncat -l 2000 -k -c 'xargs -n1 echo'

ncat is available at http://nmap.org/ncat/.

P.S. with the original the Hobbit's netcat (nc) the -c flag is not supported.

Update: -k (--keep-open) is now required to handle multiple connections.

Proxy answered 4/12, 2011 at 20:42 Comment(3)
Thanks! It works but with a minor change - we should use it without the "-p" option: ncat -l 2000 -c 'xargs -n1 echo'Swanhildas
@BinWang updated. Follow douyw link below for further explanationsProxy
xargs -n1 echo splits up lines by whitespace, but xargs -l1 echo keeps lines intact.Haver
B
36

Here are some examples. ncat simple services

TCP echo server

ncat -l 2000 --keep-open --exec "/bin/cat"

UDP echo server

ncat -l 2000 --keep-open --udp --exec "/bin/cat"
Bilection answered 10/11, 2012 at 1:53 Comment(1)
Beware though, that with --udp, ncat will keep the "connections" open and if you don't want to hit the default limit of 100 connections, then you should either increase the maximum with the --max-conns option or let the "connections" die after an idle timeout that you can set with --idle-timeout.Buckram
D
22

In case ncat is not an option, socat will also work:

socat TCP4-LISTEN:2000,fork EXEC:cat

The fork is necessary so multiple connections can be accepted. Adding reuseaddr to TCP4-LISTEN may be convenient.

Drue answered 8/3, 2016 at 1:2 Comment(0)
B
2

netcat solution pre-installed in Ubunutu

The netcat pre-installed in Ubuntu 16.04 comes from netcat-openbsd, and has no -c option, but the manual gives a solution:

sudo mknod -m 777 fifo p
cat fifo | netcat -l -k localhost 8000 > fifo

Then client example:

echo abc | netcat localhost 8000

TODO: how to modify the input string value? The following does not return any reply:

cat fifo | tr 'a' 'b' | netcat -l -k localhost 8000 > fifo

The remote shell example however works:

cat fifo | /bin/sh -i 2>&1 | netcat -l -k localhost 8000 > fifo

I don't know how to deal with concurrent requests simply however.

Bordelaise answered 29/5, 2017 at 15:55 Comment(0)
C
0

what about...

#! /bin/sh

while :; do
/bin/nc.traditional -k -l -p 3342 -c 'xargs -n1 echo'
done
Chatter answered 15/3, 2019 at 18:41 Comment(1)
while :; do /bin/nc.traditional -k -l -p 3342 -c xargs -n1 echo ; doneChatter

© 2022 - 2024 — McMap. All rights reserved.