How to access Unix Domain Sockets from the command line?

Adam Matan picture Adam Matan · Nov 28, 2014 · Viewed 25.9k times · Source

Reading a Unix Domain Socket file using Python is similar to an ordinary TCP socket:

>>> import socket
>>> import sys
>>>
>>> server_address = '/tmp/tbsocket1'  # Analogous to TCP (address, port) pair
>>> sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
>>> sock.connect(server_address)
>>> sock.recv(512)
'*** uWSGI Python tracebacker output ***\n\n'

Since UDS are not ordinary files, cat does not work on them:

$ sudo cat /tmp/tbsocket1
cat: /tmp/tbsocket1: No such device or address

Neither do curl:

$ sudo curl /tmp/tbsocket1
curl: (3) <url> malformed

How do I read or write to Unix Domain Sockets using standard command line tools like curl?

PS: In a strange coincidence, a curl patch was suggested very recently)

Answer

kev picture kev · Nov 29, 2014

You can use ncat command from the nmap project:

ncat -U /tmp/tbsocket1

To make it easy to access, you can do this:

# forward incoming 8080/tcp to unix socket
ncat -vlk 8080 -c 'ncat -U /tmp/tbsocket1'
# make a http request via curl
curl http://localhost:8080

You can also use socat:

# forward incoming 8080/tcp to unix socket
socat -d -d TCP-LISTEN:8080,fork UNIX:/tmp/tbsocket1