Home:ALL Converter>Redirecting TCP-traffic to a UNIX domain socket under Linux

Redirecting TCP-traffic to a UNIX domain socket under Linux

Ask Time:2010-01-28T03:01:43         Author:knorv

Json Formatter

Assume a legacy Linux application listening on a UNIX domain socket /tmp/foo.

In addition to communicating with this legacy application over the UNIX domain socket mechanism I want to be able to connect to it via a TCP-connection on port say 1234.

What is the easiest way to bind to TCP port 1234 and then redirect all incoming connections to the UNIX domain socket /tmp/foo?

Author:knorv,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/2149564/redirecting-tcp-traffic-to-a-unix-domain-socket-under-linux
hloroform :

In additons to @knorv's answer: with xinetd it can work like a daemon\n\n# cat /etc/xined.d/mysrv\nservice mysrv\n{\n disable = no\n type = UNLISTED\n socket_type = stream\n protocol = tcp\n wait = no\n server = /usr/bin/socat\n server_args = STDIN UNIX-CLIENT:/tmp/mysocket.sock\n bind = 127.0.0.1\n port = 1234\n}\n",
2016-06-24T12:18:32
knorv :

Turns out socat can be used to achieve this:\n\nsocat TCP-LISTEN:1234,reuseaddr,fork UNIX-CLIENT:/tmp/foo\n\n\nAnd with a bit of added security:\n\nsocat TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,su=nobody,range=127.0.0.0/8 UNIX-CLIENT:/tmp/foo\n\n\nThese examples have been tested and work as expected.",
2010-01-27T20:57:14
Brian Campbell :

Easiest? Probably Netcat (aka nc):\n\nnc -l 1234 | nc -U /tmp/foo\n\n\nThe first command listens on port 1234 for incoming connections, and pipes the resulting data to the second command. The second connects to the Unix domain socket /tmp/foo, and writes its input to that socket. Note that this will only accept a single connection, and exit as soon as that connection is dropped. If you want to keep listening for more connections, use the -k option:\n\nnc -lk 1234 | nc -U /tmp/foo\n\n\nYou can test that this is working by setting up a listener for that socket in one terminal:\n\nnc -lUk /tmp/foo\n\n\nAnd writing to it in another:\n\nnc localhost 1234\n\n\nsocat, as recommended by knorv, is more capable, but more complicated to use.",
2010-01-27T21:22:34
Aryabhatta :

You should be able to bind to TCP 1234, get a socket fd for /tmp/foo and use the select call to 'listen' for data on both 1234, and /tmp/foo. Any data written to 1234, you rewrite to /tmp/foo and vice-versa.\n\nYou now act as a proxy and transfer data back and forth.\n\nAnd here is a web-page which might help: http://osr507doc.sco.com/en/netguide/dusockC.io_multiplexing.html",
2010-01-27T19:06:11
yy