1. 程式人生 > >在python中用BaseHTTPRequestHandler模組兒時獲取客戶端的ip和埠

在python中用BaseHTTPRequestHandler模組兒時獲取客戶端的ip和埠

1、在python安裝路徑下找到E:\Program Files\Python25\Lib\SocketServer.py

2,由於python原裝模組並沒有為我們提供獲取客戶端IP地址和port的介面(至少目前我沒有找到),因此需要自己動手豐衣足食了。修改SocketServer中程式碼,在其中新增一個全域性變數,以獲取客戶端的addr。在handle_request()函式當中新增如下程式碼
程式碼如下:

application_client_addr=('192.168.0.1',9999)#全域性變數

def handle_request(self):
        """Handle one request, possibly blocking."""
        try:
            request, client_address = self.get_request()


       global application_client_addr#宣告全域性變數
       application_client_addr=client_address#獲取客戶端addr

        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)
                self.close_request(request)

3.如何呼叫呢?在你的程式當中

import SocketServer

print SocketServer.application_client_addr

取完收工!