Tornado obtains the client device information and IP address, tornadoip
The first blog about how to obtain the Client IP address is to get the client IP address in Tornado.
View the tornado httpserver. py source code and find that you can directly use self. request. remote_ip to get the client address:
def __str__(self): if self.address_family in (socket.AF_INET, socket.AF_INET6): return self.remote_ip elif isinstance(self.address, bytes): # Python 3 with the -bb option warns about str(bytes), # so convert it explicitly. # Unix socket addresses are str on mac but bytes on linux. return native_str(self.address) else: return str(self.address) def _apply_xheaders(self, headers): """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) ip = ip.split(',')[-1].strip() ip = headers.get("X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto_header = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", self.protocol)) if proto_header in ("http", "https"): self.protocol = proto_header def _unapply_xheaders(self): """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
So I think we can do this:
''' Copyright (c) HuangJunJie@SYSU(SNO13331087). All Rights Reserved. '''''' get_user-agent_and_ip.py: catch the headers and ip of the client '''import tornado.httpserverimport tornado.ioloopimport tornado.webimport tornado.optionsimport os.pathfrom tornado.options import define, optionsdefine("port", default=8888, help="run on the given port", type=int)class MainHandler(tornado.web.RequestHandler): def get(self): self.write(self.request.headers['user-agent'] +\ "\nyour current ip is: "+self.request.remote_ip)if __name__ == "__main__": application = tornado.web.Application([(r"/", MainHandler)], debug = True) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
The following results are obtained when accessing the local browser and accessing the wifi sent from the notebook using the mobile phone: