IP address of client in Python SimpleXMLRPCServer?

落花浮王杯 提交于 2019-12-01 06:22:52

As Michael noted, you can get client_address from within the request handler. For instance, you can override the __init__ function which is inherited indirectly from BaseRequestHandler.

class RequestHandler(SimpleXMLRPCRequestHandler):
    def __init__(self, request, client_address, server):
        print client_address # do what you need to do with client_address here
        SimpleXMLRPCRequestHandler.__init__(self, request, client_address, server)

The request handler itself should have a property client_address (inherited from BaseHTTPRequestHandler). From BaseHTTPRequestHandler:

Contains a tuple of the form (host, port) referring to the client’s address.

One way to pass the ip address to the request method is to override RequestHandler.decode_request_content.

decode_request_content returns a XML string. Example:

<?xml version='1.0'?>
<methodCall>
    <methodName>get_workunit</methodName>
    <params>
        <param>
            <value><int>1</int></value>
        </param>
        <param>
            <value><string>Windows</string></value>
        </param>
        <param>
            <value><string>32bit</string></value>
        </param>
    </params>
</methodCall>

Just slip another parameter in there.

class HackyRequestHandler(SimpleXMLRPCRequestHandler):
    def __init__(self, req, addr, server):
       self.client_ip, self.client_port = addr
       SimpleXMLRPCRequestHandler.__init__(self, req, addr, server)
    def decode_request_content(self, data):
       data = SimpleXMLRPCRequestHandler.decode_request_content(self, data)
       from xml.dom.minidom import parseString
       doc = parseString(data)
       ps = doc.getElementsByTagName('params')[0]
       pdoc = parseString(
            ''' <param><value>
                <string>%s</string>
                </value></param>''' % (self.client_ip,))
       p = pdoc.firstChild.cloneNode(True)
       ps.insertBefore(p, ps.firstChild)
       return doc.toxml()

and update your method signatures accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!