使用Python从HTTP POST请求中获取IP地址

14

我正在使用一个Python脚本来使用BaseHTTPServer模块搭建我的Web服务器。以下是我的服务器代码:

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:
        if self.path.endswith("/"):
        f = open(curdir + sep + "index.html")
        self.send_response(200)
        self.send_header('Content-type',    'text/html')
        self.end_headers()
        self.wfile.write("<HTML> GET OK.<BR>")
        f.close()
        return

            return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)


    def do_POST(self):
        global rootnode
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                query=cgi.parse_multipart(self.rfile, pdict)
            self.send_response(200)
            self.send_header('Content-type',    'text/html')
        self.end_headers()
        file = query.get('file')
        self.wfile.write("<HTML> POST OK.<BR>")
        f = open("data.zip", "wb")
            f.write(file[0])
            f.close()
            print("File received.")
        return

        except :
            pass

def main():
    try:
        server = HTTPServer(('', 8080), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

当我的服务器接收到POST请求时,是否有任何方法可以获取IP地址?非常感谢提前。

1个回答

21

你可以通过 self.client_address[0] 获取他们的IP地址。


当我执行 print self.client_address 时,它会给我一个 IP 地址和一个数字。那是端口号吗? - Zerhinne
@androidnoob:是的,第二个数字是客户端的端口。如果你只想要IP地址,就在末尾加上[0] - icktoofay
我明白了。非常感谢您的及时回答!我无法为此感激不尽! - Zerhinne
嗯...你能解释一下为什么无论客户端从哪里连接,我总是得到值192.168.2.50吗? - pir
@pir:你可能在应用程序前面运行了一个反向代理。一些代理会添加一个 X-Forwarded-For 头,提供连接到它的客户端的 IP 地址。 - icktoofay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接