How to make an Echo server with Bash?

2019-01-31 02:47发布

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.

标签: bash tcp netcat
4条回答
Anthone
2楼-- · 2019-01-31 03:38

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.

查看更多
成全新的幸福
3楼-- · 2019-01-31 03:42

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.

查看更多
beautiful°
4楼-- · 2019-01-31 03:50

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"
查看更多
等我变得足够好
5楼-- · 2019-01-31 03:51

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.

查看更多
登录 后发表回答