2012-02-22 94 views
5

我正在使用python脚本来使用BaseHTTPServer模块来执行我的网络服务器。下面是我的服务器代码:使用Python从HTTP POST请求获取IP地址

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地址?提前谢谢了。

回答

5

你应该可以得到他们的IP地址self.client_address[0]

+0

当我做'打印self.client_address',它给了我一个IP地址和一个数字。这是端口号吗? – androidnoob 2012-02-22 05:58:50

+0

@androidnoob:是的,第二个数字是客户的端口。如果你只想知道IP地址,就直接用'[0]'结尾。 – icktoofay 2012-02-22 05:59:37

+0

我明白了。非常感谢您的及时答复!我无法对此表示感谢! – androidnoob 2012-02-22 06:02:25

0

对于那些不使用BaseHTTPServer库self.request.remote_addr工作得很好

+0

如果python使用某些Web服务进行代理,那么这将无法正常工作,因为IP将指向代理,所以应该转发标头,例如“X-Forwarded-For” – moka 2014-08-29 10:37:37

相关问题