The following is a code example to implement a tunnel mode HTTP proxy using Python:
```python
import socket
def handle_client(client_socket):
# Receive client request
request = client_socket.recv(4096)
# Parse the request header to get the target host and port number
host = request.split(b'\r\n')[1].split(b' ')[1]
port = 80
# Create a connection to the target host
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((host, port))
# Send the client request to the target host
remote_socket.send(request)
# Loop to receive the response from the target host and send it to the client
while True:
response = remote_socket.recv(4096)
if len(response) > 0:
client_socket.send(response)
else:
break
# Close the connection
remote_socket.close()
client_socket.close()
def proxy_server():
# Create a listening socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('0.0.0.0', 8888))
server_socket. listen(5)
print('[*] Listening on 0.0.0.0:8888')
while True:
# Accept client connection
client_socket, addr = server_socket.accept()
print('[*] Accepted connection from: %s:%d' % (addr[0], addr[1]))
# Create a new thread to handle client requests
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == '__main__':
proxy_server()
```
In the above code, we used the socket module of Python to implement the proxy server. First, we create a listening socket, waiting for clients to connect. When a client connects to the proxy server, we create a new thread to handle the client request. In the function that handles the client request, we first parse the request header to get the target host and port number. We then create a connection to the target host and send the client request to the target host. Next, we loop to receive the response from the target host and send the response to the client. Finally, we close the connection.