我正在使用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地址?提前謝謝了。
當我做'打印self.client_address',它給了我一個IP地址和一個數字。這是端口號嗎? – androidnoob 2012-02-22 05:58:50
@androidnoob:是的,第二個數字是客戶的端口。如果你只想知道IP地址,就直接用'[0]'結尾。 – icktoofay 2012-02-22 05:59:37
我明白了。非常感謝您的及時答覆!我無法對此表示感謝! – androidnoob 2012-02-22 06:02:25