首页 > 代码库 > tornado获得客户端设备信息和ip地址

tornado获得客户端设备信息和ip地址

最初看到的关于如何获取客户端ip地址的博客是在Tornado获取客户端IP

然后 查看tornado源码,发现可以直接用self.request.remote_ip获得客户端地址:

 

    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

于是觉得可以这样子做:

‘‘‘ 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()

 在本地的浏览器访问和使用手机该笔记本发射的wifi访问得到了如下结果:

 

tornado获得客户端设备信息和ip地址