-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxyserver2.py
82 lines (77 loc) · 3.05 KB
/
proxyserver2.py
1
2
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
75
76
77
78
79
80
81
82
from socket import *
import sys
if len(sys.argv) <= 1:
print('Usage : "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server')
sys.exit(2)
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerPort = 8888
tcpSerSock.bind(("", tcpSerPort))
tcpSerSock.listen(5)
while 1:
# Start receiving data from the client
print('Listening and Ready to serve...')
tcpCliSock, addr = tcpSerSock.accept()
print('Received a connection from:', addr)
message = tcpCliSock.recv(1024)
print(message)
# Extract the filename from the given message
print(message.split()[1])
filename = message.split()[1].partition("/")[2]
print(filename)
fileExist = "false"
filetouse = "/" + filename
print(filetouse)
try:
# Check wether the file exist in the cache
f = open(filetouse[1:], "r")
outputdata = f.readlines()
fileExist = "true"
# ProxyServer finds a cache hit and generates a response message
tcpCliSock.send("HTTP/1.0 200 OK\r\n")
tcpCliSock.send("Content-Type:text/html\r\n")
# Fill in start.
for i in range(0, len(outputdata)):
tcpCliSock.send(outputdata[i])
# Fill in end.
print('Read from cache')
# Error handling for file not found in cache
except IOError:
if fileExist == "false":
# Create a socket on the proxyserver
c = socket(AF_INET, SOCK_STREAM) # Fill in start. Fill in end.
hostn = filename.replace("www.", "", 1)
print(hostn)
try:
# Connect to the socket to port 80
# Fill in start.
c.connect((hostn, 80))
# Fill in end.
# Create a temporary file on this socket and ask port 80 for the file requested by the client
fileobj = c.makefile('r', 0)
fileobj.write("GET " + "http://" + filename + "HTTP/1.0\n\n")
# Read the response into buffer
# Fill in start.
buff = fileobj.readlines()
# Fill in end.
# Create a new file in the cache for the requested file.
# Also send the response in the buffer to client socket and the corresponding file in the cache
tmpFile = open("./" + filename, "wb")
# Fill in start.
for i in range(0, len(buff)):
tmpFile.write(buff[i])
tcpCliSock.send(buff[i])
# Fill in end.
except:
print("Illegal request")
else:
# HTTP response message for file not found
# Fill in start.
print("404 Error file not found")
# Fill in end.
# Close the client and the server sockets
tcpCliSock.close()
if __name__ == "__main__":
main()
# proxyserver2.py 127.0.0.1
# http://localhost:8888/www.yahoo.com