3

I'm writing a simple xmlrpc programe in python. something like the following:


def foo(data):

    # I want get the calling client's IP address here... How can I ?

server=SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_function(foo)

server.handle_request()

As can be seen in the above, I want to get the client IP address in the registed function "foo", how can I ?

John Wang
  • 4,562
  • 9
  • 37
  • 54

1 Answers1

3

You may do so by subclassing the server (and possibly the handler, too). E.g.:

class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
    def process_request(self, request, client_address):
        self.client_address = client_address
        return SimpleXMLRPCServer.SimpleXMLRPCServer.process_request(
            self, request, client_address)

server=SimpleXMLRPCServer.MyXMLRPCServer((host, port))

Now server.client_address gives you the desired data. Note that this direct, short coding only works for the single-threaded case (which you're using anyway by choosing the simple server in your code) -- the need to work with the handler comes in if you want to go multi-threaded.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • thank you Alex. But how can I access the instance varible "client_address" in the registed function "foo" ? – John Wang Jul 13 '10 at 10:20
  • @john, `server.client_address`, of course -- the instance is named `server`, so its instance variables are accessed as `server.whatever`. – Alex Martelli Jul 13 '10 at 14:05
  • this is slighly better than to instantiate the request handler, bind such client_address to the server instance is easier to access, which I had a similar reqeust, to let regist functions behave differently based on client side ip address, for other's reference. – Jack Wu Nov 30 '18 at 05:27