| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 
 |  
#!/usr/bin/env python
 
import socket
import thread
import sys
 
def get_line(field, data) :
	lines = data.split("\n")
	for line in lines :
		if line.split(":")[0] == field :
			return line
	return ""
 
def get_host(data) :
	host_line = get_line("Host", data);
	port = 80
	if len(host_line.split(" ")) > 1 :
		host = host_line.split(" ")[1]
		arr = host.split(":")
		if len(arr) > 1 :
			host = arr[0]
			port = arr[1]
		else :
			host = host[:-1]
	else :
		host = ""
		port = 0
	return (host, port)
 
def http_proxy(conn, data, client_addr) :
	#On récupère l'hote et le port dans le champ "Host" de la requête HTTP.
	(host, port) = get_host(data)
	if host != "" :
		try :
			#On se connecte au serveur pour lui envoyer la requête HTTP.
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.connect((socket.gethostbyname(host), int(port)))
			s.send(data)
			while 1 : 
				reply = s.recv(8192)
				test = reply
				if (len(reply) > 0) :
					#On envoit la réponse du serveur au client.
					conn.send(reply)
					print "Send %d bytes from %s" % (len(reply), host)
				else :
					s.close()
					break
		except socket.error, (value, message) :
			s.close()
			conn.close()
			print value, message
			sys.exit(1)
 
def main():
	try :
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.bind(('', 8080))
		s.listen(100)
	except socket.error, (value, message) :
		if s : 
			s.close()
		print "Socket error : ", message
	#On accepte toutes les connexions.
	while 1 :
		conn, client_addr = s.accept()
		data = conn.recv(8192)
		#Pour chaque connexion, on fait un thread.
		thread.start_new_thread(http_proxy, (conn, data, client_addr))
	s.close()
 
if __name__ == "__main__" :
	main() | 
Partager