How to get client IP from SimpleHTTPServer

Deadly 提交于 2019-12-11 00:21:19

问题


Building a simple file server using the SimpleHTTPServer module in Python, however I'm running into issues when trying to get the IP from a connecting client. Here is what I have..

import SimpleHTTPServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", 8080), Handler)

print "Serving local directory"

while True:
    httpd.handle_request()
    print Handler.client_address[0]

When a client connects I get..

AttributeError: class SimpleHTTPRequestHandler has no attribute 'client_address'

I know this is because I haven't instantiated the class yet, but is there another way to get the IP from the client without having to create a handler instance? The client's IP is outputted to the console when a connection is made, I just need a way to grab that IP within my script.

Thanks!


回答1:


Indeed, the Handler class object is unrelated to specific instances. Set up your own handler class, like this:

import SimpleHTTPServer
import SocketServer


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

print("Serving local directory")
httpd = SocketServer.TCPServer(("", 8080), MyHandler)

while True:
    httpd.handle_request()


来源:https://stackoverflow.com/questions/37055005/how-to-get-client-ip-from-simplehttpserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!