简体   繁体   English

用http.server如何访问被叫IP地址?

[英]With http.server how to access the called IP address?

This must be very simple, but can't find any reference on documentation and google isn't helping. 这必须非常简单,但是找不到文档上的任何参考,而Google也无济于事。 On the below example 在下面的例子中

from http.server import BaseHTTPRequestHandler, HTTPServer

PORT_NUMBER = 80

class myHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        print(self.path)   # <<<<<<<< Here
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write(bytes("Hello world", "utf8"))

server = HTTPServer(('', PORT_NUMBER), myHandler)
server.serve_forever()

If my machine has multiple interfaces, the binding is done with 0.0.0.0. 如果我的机器有多个接口,则绑定将使用0.0.0.0完成。 How can I on the request handler retrieve the IP which was received the socket connection ? 如何在请求处理程序上检索套接字连接收到的IP?

In the do_* methods of an instance of BaseHTTPRequestHandler , self.request is the socket.socket object associated with the request. BaseHTTPRequestHandler实例的do_*方法中, self.request是与请求关联的socket.socket对象。 You can get the server side of the socket with self.request.getsockname() , which will give you a tuple of the server IP and port that the client connected to. 您可以使用self.request.getsockname()获得套接字的服务器端,这将为您提供客户端连接的服务器IP和端口的元组。 Therefore the IP address will be: 因此,IP地址为:

self.request.getsockname()[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM