Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting TCP-traffic to a UNIX domain socket under Linux

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?

like image 206
knorv Avatar asked Jan 27 '10 19:01

knorv


People also ask

Do Unix sockets use TCP?

Socket Use In PracticeUnix sockets are usually used as an alternative to network-based TCP connections when processes are running on the same machine.

What is Unix domain socket path?

UNIX domain sockets are named with UNIX paths. For example, a socket might be named /tmp/foo. UNIX domain sockets communicate only between processes on a single host.

What is Socat command in Linux?

Socat is a flexible, multi-purpose relay tool. Its purpose is to establish a relationship between two data sources, where each data source can be a file, a Unix socket, UDP, TCP, or standard input.

Are UNIX sockets faster than TCP?

Unix domain sockets are often twice as fast as a TCP socket when both peers are on the same host. The Unix domain protocols are not an actual protocol suite, but a way of performing client/server communication on a single host using the same API that is used for clients and servers on different hosts.


2 Answers

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.

like image 180
knorv Avatar answered Sep 23 '22 05:09

knorv


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.

like image 43
Brian Campbell Avatar answered Sep 24 '22 05:09

Brian Campbell