0rpc / zerorpc-python

zerorpc for python
http://www.zerorpc.io
Other
3.17k stars 380 forks source link

How to fetch socket peername #181

Open losintikfos opened 6 years ago

losintikfos commented 6 years ago

Is it possible to fetch remote peer address i.e possibly doing something similar to below:

import zerorpc

class Rpc(object):
    def __init__(self):
         super(Rpc, self).__init__()

     @property
     def peer(self):
         return self.socket.getpeername()

rpc = zerorpc.Server(Rpc())
rpc.bind("tcp://0.0.0.0:2222")
losintikfos commented 6 years ago

In my quest to fetch the peer address - I am passing instance ofg zerorpc.Server to a middleware class. And then within the server_before_exec function trying something like this:

    socket = self.server._events._socket.get_monitor_socket()
    msg = socket.recv_multipart(0)
    src_fd = msg.get(zmq.SRCFD)
    src_sock = s.socket(fileno=src_fd)
    print( "Peer address: %s" % src_sock.getpeername())

The problem is - the call to socket.recv_multipart(0) blocks forever. Anyone have a clue how to achieve something like this?

bombela commented 6 years ago

You would have to read the monitor socket asynchronously. For this you need to use zeromq.green or come up with your own async io wrapper similar to gevent_zmq.py

http://api.zeromq.org/4-2:zmq-socket-monitor

But anyway, here is what the doc says about the ZMQ_EVENT_CONNECTED event:

The socket has successfully connected to a remote peer. The event value is the file descriptor (FD) of the underlying network socket. Warning: there is no guarantee that the FD is still valid by the time your code receives this event.

You should probably not call getpeername() on a random integer value.

Conclusion: you cannot get the peer of a zeromq connection.