How do i get the client ip address on a python server

Viewed 1231

I have a basic python server up using http.server in Python 3, not simplehttpserver

import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

And I need to get the clients IP address when they send a request, can anyone help me. Thank you in advance.

1 Answers

You can port that duplicate answer to Python 3 by fixing up the imports:

import http.server
import socketserver


class MyHandler(http.server.SimpleHTTPRequestHandler):
    def handle_one_request(self):
        print(self.client_address[0])
        return super().handle_one_request()


httpd = socketserver.TCPServer(("", 8080), MyHandler)

while True:
    httpd.handle_request()
Related