diff --git a/tornado/httpserver.py b/tornado/httpserver.py index 74f1a8ac..10723590 100644 --- a/tornado/httpserver.py +++ b/tornado/httpserver.py @@ -322,7 +322,7 @@ class HTTPRequest(object): .. attribute:: protocol The protocol used, either "http" or "https". If `HTTPServer.xheaders` - is seet, will pass along the protocol used by a load balancer if + is set, will pass along the protocol used by a load balancer if reported via an ``X-Scheme`` header. .. attribute:: host @@ -362,6 +362,8 @@ class HTTPRequest(object): # Squid uses X-Forwarded-For, others use X-Real-Ip self.remote_ip = self.headers.get( "X-Real-Ip", self.headers.get("X-Forwarded-For", remote_ip)) + if not self.__valid_ip(self.remote_ip): + self.remote_ip = remote_ip # AWS uses X-Forwarded-Proto self.protocol = self.headers.get( "X-Scheme", self.headers.get("X-Forwarded-Proto", protocol)) @@ -457,3 +459,14 @@ class HTTPRequest(object): args = ", ".join(["%s=%r" % (n, getattr(self, n)) for n in attrs]) return "%s(%s, headers=%s)" % ( self.__class__.__name__, args, dict(self.headers)) + + def __valid_ip(self, ip): + try: + address = socket.inet_pton(socket.AF_INET, ip) + except socket.error: + try: + address = socket.inet_pton(socket.AF_INET6, ip) + except socket.error: + return False + + return True