How to listen for multiple tcp connection using nc

风流意气都作罢 提交于 2019-12-03 14:43:15

问题


How to create a TCP connection using nc which listens to multiple hosts?

nc -l -p 12345

回答1:


Simultaneous connections are not possible with netcat. You should use something like ucspi-tcp's tcpserver tool or leverage xinetd since you're on Linux.

See: https://superuser.com/questions/232747/netcat-as-a-multithread-server

Consecutive connections could be handled through a shell script that restarts netcat after it finishes.




回答2:


ncat can do it.

E.g. ncat --broker --listen -p 12345 will distribute all incoming messages to all other clients (think of it as a hub).




回答3:


I recommend socat as nc alternative.

For OP's problem, socat - TCP-LISTEN:12345,fork,reuseaddr can do the job.




回答4:


-k
Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.




回答5:


This is an incomplete answer, because I haven't got it working. Arguably more of a question, in fact. Maybe someone else can finish it off.

First of all, it seems there are different versions of netcat. I'm on Ubuntu, so I've probably got the version that came with Ubuntu. When I nc -h, it says this:

OpenBSD netcat (Debian patchlevel 1.187-1ubuntu0.1)

When I run man nc, it says this:

-F      Pass the first connected socket using sendmsg(2) to stdout and exit.  This
        is useful in conjunction with -X to have nc perform connection setup with
        a proxy but then leave the rest of the connection to another program (e.g.
        ssh(1) using the ssh_config(5) ProxyUseFdpass option).

It seems to me that this means that, instead of doing the usual thing with stdin and stdout, it just prints something to stdout. That something could then be used by another process to do the actual connection to the client.

Unfortunately, -F has no effect that I can see. So maybe I'm doing it wrong. Or maybe there's some secret pipe somewhere that I have to listen to, or a supplementary argument they forgot to document. Or maybe I happen to have a broken build of netcat, and it works for everyone else who's on Ubuntu.

In combination with the -k option (or, failing that, a while-true loop), this would allow many different clients to have separate connections. Suppose you have an executable called handle_connection, which takes as arguments an in file descriptor from a client and an out file descriptor to the client, and spawns a subprocess which communicates with the client. Then the server script might look like this:

nc -lkF $host $port | while read in out ; do
    handle_connection $in $out ;
done


来源:https://stackoverflow.com/questions/29728151/how-to-listen-for-multiple-tcp-connection-using-nc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!