user2123288
user2123288

Reputation: 1119

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. 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. How can I on the request handler retrieve the IP which was received the socket connection ?

Upvotes: 1

Views: 711

Answers (1)

glibdud
glibdud

Reputation: 7840

In the do_* methods of an instance of BaseHTTPRequestHandler, self.request is the socket.socket object associated with the request. 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. Therefore the IP address will be:

self.request.getsockname()[0]

Upvotes: 3

Related Questions