import socket
import threading
import sys

def server_loop(local_host, local_port, target_host, target_port):
	server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
		server.bind((local_host, local_port))
	except:
		print "[!] Failed to connect to %s:%d" % (local_host, local_port)
		sys.exit(0)

	server.listen(5)
	while True:
		client_sock, addr = server.accept()
		print "[===>] Recieving incoming connection from %s:%d" % (addr[0], addr[1])
		proxy_thread = threading.Thread(target=proxy_handler, args=(client_sock, target_host, target_port))
		proxy_thread.start()
	client_sock.close()

def proxy_handler(client_socket, target_host, target_port):
	target_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
		target_server.bind((target_host, target_port))
	except:
		print "[!] Failed to connect to %s:%d" % (target_host, target_port)
		sys.exit(0)

	target_server.listen(5)
	
	while True:
		target_socket, target_addr = target_server.accept()
		target_socket.send("Type something")
		target_buffer = target_socket.recv(1024)
		print "[<===] Recieving data from %s:%d" % (target_host, target_port)
		print(target_buffer)
		return(target_buffer)
		

def forward(proxy_handler):
	if len(proxy_handler):
		print "Does that even work ? "
		server.send(proxy_handler)
	else:
		sys.exit(0)

def main():
	if len(sys.argv[1:]) != 4:
		print "Usage: python script.py 127.0.0.1 8888 127.0.0.1 9999"
		sys.exit(0)

	local_host = sys.argv[1]
	local_port = int(sys.argv[2])

	target_host = sys.argv[3]
	target_port = int(sys.argv[4])

	server_loop(local_host, local_port, target_host, target_port)
	forward()

if __name__ == '__main__':
	main()
