Search code examples
pythonsocketssocat

Pipe Unix Socket to a random TCP socket using Python and may be Socat


I want to pipe a TCP socket to Unix socket I could do this using socat like this

socat TCP-LISTEN:1234 UNIX-CONNECT:test.socket

But the problem here, I don't want to specify the port number myself I want the OS to choose a free port for me, yet I can still know the port.

I wrote this script, that doesn't work, but may illustrate what I want to do

def bind(unix_sock_file):
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_socket.bind(('', 0))
    tcp_socket.listen(1)
    cmd = 'socat - UNIX-CONNECT:%s' % unix_sock_file
    Popen(cmd, shell=True, stdin=tcp_socket, stdout=tcp_socket, close_fds=True)
    return tcp_socket.getsockname()

The error I got is:

2012/09/11 15:34:39 socat[26509] E read(0, 0x1e97a90, 8192): Transport endpoint is not connected

Note#1: I accept any other solution other that socat too
Note#2: This script should pipe a Web Server listening on the Unix Socket, and a Web Browser connecting to the generated TCP port.

Thanks in advance


Solution

  • I figured out a simpler way to it, here it is:

    def bind(unix_sock_file):
        CMD = "socat TCP-LISTEN:0 UNIX-CONNECT:%s" % unix_sock_file
        pid = Popen(CMD, shell=True, close_fds=True).pid
        return psutil.Process(pid).get_children()[0].get_connections()[0].local_address[1]