How to set up a 'listening' Unix domain socket

Chris Angelico rosuav at gmail.com
Mon Mar 22 07:26:55 EDT 2021


On Mon, Mar 22, 2021 at 9:11 PM Robert Latest via Python-list
<python-list at python.org> wrote:
>
> Hello,
>
> I'm trying to set up a server that receives data on a Unix domain socket using
> the code below.
>
> import os from socketserver import UnixStreamServer, StreamRequestHandler
>
> SOCKET = '/tmp/test.socket'
>
> class Handler(StreamRequestHandler):
>
>     def handle(self): data = selr.rfile.read() print(data)
>
> if os.path.exists(SOCKET): os.unlink(SOCKET) with UnixStreamServer(SOCKET,
>     Handler) as server: server.serve_forever()

Hmm, your formatting's messed up, but the code looks fine to me. (Be
aware that you seem to have a "selr" where it should be "self".)

> However, when I try to send somthing to that socket, I get this error message:
>
> $ echo "Hello" | socat - UNIX-SENDTO:/tmp/test.socket 2021/03/22 11:03:22
> socat[2188] E sendto(5, 0x55a22f414990, 6, 0, AF=1 "/tmp/test.socket", 18):
> Protocol wrong type for socket
>

Not familiar with socat, but here's some simple Python code to trigger
your server:

>>> import socket
>>> sock = socket.socket(socket.AF_UNIX)
>>> sock.connect("/tmp/test.socket")
>>> sock.send(b"Hello, world")
12
>>> sock.close()
>>>

Once you close the socket, the request handler should respond.

ChrisA


More information about the Python-list mailing list