def getClientIP(request, useForwardedHeader=False):
"""Get the client's IP address from the ``'X-Forwarded-For:'``
header, or from the :api:`request <twisted.web.server.Request>`.
:type request: :api:`twisted.web.http.Request`
:param request: A ``Request`` for a :api:`twisted.web.resource.Resource`.
:param bool useForwardedHeader: If ``True``, attempt to get the client's
IP address from the ``'X-Forwarded-For:'`` header.
:rtype: ``None`` or :any:`str`
:returns: The client's IP address, if it was obtainable.
"""
ip = None
if useForwardedHeader:
header = request.getHeader("X-Forwarded-For")
if header:
ip = header.split(",")[-1].strip()
if not isIPAddress(ip):
log.msg("Got weird X-Forwarded-For value %r" % header)
ip = None
else:
ip = request.getClientIP()
return ip
评论列表
文章目录