-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_server.py
More file actions
80 lines (64 loc) · 2.27 KB
/
Copy pathproxy_server.py
File metadata and controls
80 lines (64 loc) · 2.27 KB
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
#!/usr/bin/env python3
import socket
import time
#define address & buffer size
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
#get host information
def get_remote_ip(host):
print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
print (f'Ip address of {host} is {remote_ip}')
return remote_ip
#send data to server
def send_data(serversocket, data):
print("Sending data")
try:
serversocket.sendall(data)
except socket.error:
print ('Send failed')
sys.exit()
print("Data sent successfully")
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#QUESTION 3
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#bind socket to address
s.bind((HOST, PORT))
#set to listening mode
s.listen(2)
#continuously listen for connections
while True:
conn, addr = s.accept()
print("Connected by", addr)
#recieve data, wait a bit, then send it back
full_data = conn.recv(BUFFER_SIZE)
time.sleep(0.5)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as t:
#define address info, payload, and buffer size
host = 'www.google.com'
port = 80
buffer_size = 1024
remote_ip = get_remote_ip(host)
t.connect((remote_ip , port))
print (f'Socket Connected to {host} on ip {remote_ip}')
#send the data and shutdown
send_data(t, full_data)
t.shutdown(socket.SHUT_WR)
#continue accepting data until no more left
google_data = b""
while True:
data = t.recv(buffer_size)
if not data:
break
google_data += data
print("Sending proxy data to client connected.")
conn.sendall(google_data)
conn.close()
if __name__ == "__main__":
main()