Redirecting TCP-traffic to a UNIX domain socket un

2019-01-30 02:16发布

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?

5条回答
不美不萌又怎样
2楼-- · 2019-01-30 02:49

Easiest? Probably Netcat (aka nc):

nc -l 1234 | nc -U /tmp/foo

The 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:

nc -lk 1234 | nc -U /tmp/foo

You can test that this is working by setting up a listener for that socket in one terminal:

nc -lUk /tmp/foo

And writing to it in another:

nc localhost 1234

socat, as recommended by knorv, is more capable, but more complicated to use.

查看更多
Evening l夕情丶
3楼-- · 2019-01-30 02:53

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.

You now act as a proxy and transfer data back and forth.

And here is a web-page which might help: http://osr507doc.sco.com/en/netguide/dusockC.io_multiplexing.html

查看更多
再贱就再见
4楼-- · 2019-01-30 02:56

Not tried it : but it looks like 'lighttpd' can do this for you:

http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore

查看更多
We Are One
5楼-- · 2019-01-30 03:03

In additons to @knorv's answer: with xinetd it can work like a daemon

# cat /etc/xined.d/mysrv
service mysrv
{
 disable = no
 type = UNLISTED
 socket_type = stream
 protocol = tcp
 wait = no
 server = /usr/bin/socat
 server_args = STDIN UNIX-CLIENT:/tmp/mysocket.sock
 bind = 127.0.0.1
 port = 1234
}
查看更多
淡お忘
6楼-- · 2019-01-30 03:08

Turns out socat can be used to achieve this:

socat TCP-LISTEN:1234,reuseaddr,fork UNIX-CLIENT:/tmp/foo

And with a bit of added security:

socat TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,su=nobody,range=127.0.0.0/8 UNIX-CLIENT:/tmp/foo

These examples have been tested and work as expected.

查看更多
登录 后发表回答