利用Socket编写HTTP代理(很不完美)
问题:
接收的数据如果大于缓冲,则将无法完整接收数据,但是如果用循环方式来接收,代理与浏览器之间的交互似乎存在问题。
1 from concurrent.futures import thread 2 import optparse 3 import sys 4 import socket 5 import threading 6 7 class MyTCPProxy: 8 def __init__(self) -> None: 9 self.port = self.get_params() 10 11 def get_params(self): 12 parser = optparse.OptionParser("Usage: < Program > -p local port to listen") 13 parser.add_option('-p', '--port', dest='port', type='int', help='Specify local port to listen') 14 options, args = parser.parse_args() 15 if options.port is None: 16 print(parser.usage) 17 sys.exit(0) 18 return options.port 19 20 def recvdata(self, c_socket): 21 22 return c_socket.recv(4096).decode('utf-8') 23 24 25 def proxy_handler(self, local_client_socket, client_addr): 26 remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 27 remote_socket.connect(('192.168.140.144',80)) 28 print('[-] Connected from %s' % client_addr) 29 while True: 30 data_from_local = self.recvdata(local_client_socket) 31 32 remote_socket.send(data_from_local.encode('utf-8')) 33 data_from_remote = self.recvdata(remote_socket) 34 local_client_socket.send(data_from_remote.encode('utf-8')) 35 36 37 38 39 def run(self): 40 try: 41 local_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 42 local_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 43 local_socket.bind(('0.0.0.0', self.port)) 44 local_socket.listen(5) 45 while True: 46 local_client_socket, client_addr = local_socket.accept() 47 t = threading.Thread(target=self.proxy_handler, args=(local_client_socket,str(client_addr))) 48 t.start() 49 except Exception as e: 50 print(e) 51 sys.exit(0) 52 53 54 if __name__ == '__main__': 55 mytcpproxy = MyTCPProxy() 56 mytcpproxy.run() 57
STRIVE FOR PROGRESS,NOT FOR PERFECTION