Write proxy web server using socket in python - python

This is my code for my seminar at university in computer network course.
Require: write a proxy web server. Receive HTTP request from the browser port 8888 and send HTTP request to web server port 80. It seems like I had trouble sending request to web server.
Could you show me my error in this situation?
Many thanks
import socket
import sys
import _thread
import traceback
import ssl
def CreateServer(host, port):
Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server.bind((host,port))
Server.listen(5)
return Server
def ReadRequest(Client):
re = ""
Client.settimeout(10.0)
try:
re = Client.recv(1024).decode()
while (re):
re = re + Client.recv(1024).decode()
except socket.timeout: # fail after 1 second of no activity
if not re:
print("Didn't receive data! [Timeout]")
finally:
return re
#2. Client connect Server + 3. Read HTTP Request
def ReadHTTPRequest(Server):
re = ""
while (re == ""):
Client, address = Server.accept()
print("Client: ", address," da ket noi toi Server")
re = ReadRequest(Client)
return Client,address, re
def proxy_server(webserver, port, conn, data, addr):
print("{} {} {} {}".format(webserver, port, conn, addr))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10.0)
s.connect((webserver, port))
s.sendall(data)
while 1:
reply = s.recv(1024)
if len(reply) > 0:
conn.send(reply)
print("[*] Request sent: {} > {}".format(addr[0],webserver))
else:
break
s.close()
conn.close()
except Exception as e:
print(e)
traceback.print_exc()
s.close()
conn.close()
sys.exit(1)
def conn_string(Client,Request,addr):
try:
#print(addr)
first_line=Request.split('\n')[0]
url=first_line.split(" ")[1]
http_pos=url.find("://")
if http_pos==-1:
temp=url
else:
temp=url[(http_pos+3):]
port_pos=temp.find(":")
webserver_pos=temp.find("/")
if webserver_pos == -1:
webserver_pos = len(temp)
webserver = ""
port = -1
if port_pos == -1 or webserver_pos < port_pos:
port = 80
webserver = temp[:webserver_pos]
else:
port = 80
#port = int(temp[(port_pos + 1):][:webserver_pos - port_pos -1])
webserver = temp[:port_pos]
proxy_server(webserver,port,Client,Request.encode(),addr)
except Exception as e:
print (e)
traceback.print_exc()
if __name__=="__main__":
try:
Server=CreateServer("",8888)
print("[*] Intializing socket. Done.")
print("[*] Socket binded successfully...")
print("[*] Server started successfully [{}]".format(8888))
except Exception as e:
print(e)
sys.exit(2)
while True:
try:
Client,addr,Request=ReadHTTPRequest(Server)
print("---------HTTP request: ")
print(Request)
_thread.start_new_thread(conn_string,(Client,Request,addr))
except KeyboardInterrupt:
Server.close()
print("\n[*] Shutting down..")
sys.exit()
Server.close()
[1]: https://i.stack.imgur.com/216ZO.png

You are simply forwarding the original request to the server, i.e. with the full URL inside the request:
GET http://ktdbcl.hcmus.edu.vn/ HTTP/1.1
Host: ktdbcl.hcmus.edu.vn
...
Instead only the path should be forwarded:
GET / HTTP/1.1
Host: ktdbcl.hcmus.edu.vn
...
Apart from that the reading of request and response is severely broken. You don't properly parse the HTTP protocol but instead simply wait some time and treat no data for some seconds as end of message. Since today multiple requests and responses will be done over the same connection your code will thus severely slow down any browsing.
Instead of waiting for multiple seconds for no data as the marker for end of request/response you should properly parse the HTTP protocol and wait for the appropriate end of request marker defined by the HTTP standard - see RFC 7230.

Related

No response from the sensor when connecting to the server

So i am trying to get the data from a pressure sensor Boditrak. It is connected via USB but I am not sure which port is it using... When I am connecting it I have this Data Port this is how I see it. It has its own software, but I need to get it through Python.
This is the code that I wrote:
import socket
serverAddress = 'http://localhost/api'
serverPort = 63342
bufferSize = 4096
def connect(self):
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print("Connecting to server")
s.connect((serverAddress, serverPort))
print("Connected to server\n")
response = s.recv(bufferSize)
print(response.decode("utf-8"))
Now I am not sure I am doing the right thing... but I am not sure how am I supposed to get it. Any help is appreciated.
Also the data looks like this accessed in google chrome and I get every second a new frame
When I am running the script in terminal I get nothing.
When I am reading the manual it says: "The DataPort device communicates with client devices (PC, tablet, phones) over a wifi network using a REST API. The primary role of the DataPort device is to scan one or more Boditrak sensor mats at a prescribed frequency and store those readings in a buffer"
Also do I need to have a server side and a client side? If yes, how is it supposed to look like?
Thank you!
PS. This is the live data that I want to get
Maybe I should call this GET /api/sse HTTP/1.1. But how?
For example, i took another approach but still no answer...
import socket
from urllib import parse
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = parse.urlparse('http://localhost/api')
s.connect((url[1], 80))
msg = 'GET' + 'http://localhost/api' + 'HTTP/1.1\r\n\r\n'
s.send(msg.encode('utf-8'))
response = s.recv(4096)
data = response.decode('utf-8')
print(data)
if __name__ == "__main__":
connect()
I get the following answer:
b''
UPDATE: I get some data now. Here is the code:
import socket #for sockets
import sys #for exit
def connect():
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Failed to create socket')
sys.exit()
print('Socket Created')
host = '127.0.0.1';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print('Hostname could not be resolved. Exiting')
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
#Send some data to remote server
message2 = b"GET /api/sse HTTP/1.1\r\n\r\n"
try:
# Set the whole string
s.sendall(message2)
except socket.error:
# Send failed
print('Send failed')
sys.exit()
print('Message send successfully')
# Now receive data
reply2 = s.recv(16384)
print('Frames:', reply2.decode())
if __name__ == "__main__":
connect()
And the reply:
Socket Created
Socket Connected to 127.0.0.1 on ip 127.0.0.1
Message send successfully
Frames: Access-control-allow-origin: *
Access-control-allow-methods: GET, OPTIONS
Content-type: application/json
Cache-control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Content-Length: 2583
{
"device":{ "class":"Boditrak DataPort", "name":"DataPort-******", "id":"*********", "address":"127.0.0.1", "model":"wia" },
"sensors":[ { "name":"**********", "columns":32, "rows":32, "width":470, "height":470, "minimum":0, "maximum":200, "units":"mmHg" } ],
"frames":[ { "id":719, "time":"2021-04-19 16:19:47.041", "readings":[ [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0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ated":true,
"sensorsRequired":0,
"others":[ ]
}
I have to figure it out how to get it continuously. Still sees the last frame...
Last update!
import socket #for sockets
import sys #for exit
import json
import time
t_end = time.time() + 60 * 0.2
def connect():
#create an INET, STREAMing socket
try:
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Failed to create socket')
sys.exit()
print('Socket Created')
host = '127.0.0.1';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print('Hostname could not be resolved. Exiting')
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
message2 = b"GET /api/sse HTTP/1.1\r\n\r\n"
try:
# Set the whole string
s.sendall(message2)
except socket.error:
# Send failed
print('Send failed')
sys.exit()
print('Message send successfully')
while time.time() < t_end:
reply2 = s.recv(4096).decode('utf-8')
response = json.dumps(reply2)
print(response)
if __name__ == "__main__":
connect()
This code is working and it is giving me data in real time. I encountered problems with an error: [WinError 10053] An established connection was aborted by the software in your host machine -- and after I deactivated my antivirus it works.
Heading
To ensure your script runs in the terminal you'll need to tell python to execute your method. To do that you can use an import guard. Add the following to the bottom of your file. This'll ensure that your connect method executes.
if __name__ == "__main__":
connect()
Given that you can access your data stream through the browser, you could make your life easier by using the requests library instead of working with sockets. It has the potential to save time by handling low level socket work for you.
For example:
import time
import requests
def connect():
url = 'http://localhost/api'
wait_time = 1
while True:
time.sleep(wait_time) # wait for 1s
r = requests.get(url) # get data
# print output to console
​print(r.text) # text based output
print(r.json()) # json output <- probably what you need given the screenshot
if __name__ == "__main__":
connect()

TCP Connection through IP Addresses & Port in Python

We're trying to establish a TCP connection in Python 3.8, where we want each machine to become a client and a server at the same time, so that each machine can send and receive messages. With this code, we can send and receive data (sometimes), but we have noticed that each machine can send messages to the first ip address in the IPs list, but the rest are neglected.
Perhaps there's a better way than this to establish a TCP Connection, so we can send data to each other?
All three sections (Server, Client & Sharing Distribution) of codes are attached to a python program that each machine is running.
Start Distribution:
Here server socket is initiated, and we start threads for each ip-address we want to connect to.
def start_distributed_sharing(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serv.bind(('0.0.0.0', 44445))
self.serv.listen(5)
MAX_CONNECTION = 5
IPs = ['{ip-address}', '{ip-address}', '{ip-address}', ]
client_threads = []
for ip in IPs:
client_threads.append(threading.Thread(target=self.client, args=(ip,)))
for i in range(0, len(client_threads)):
client_threads[i].start()
print("Clients is running")
while True:
conn, addr = self.serv.accept()
server_thread = threading.Thread(target=self.server, args=(conn, addr,))
server_thread.start()
print("New connection to server created!")
Server:
Each Machine starts their own server, and waits for a client to connect
def server(self, conn, addr):
while True:
data = ''
try:
data = conn.recv(4096)
except Exception:
print("Server: Lost a connection... Retrying...")
time.sleep(5)
break
if not data: break
try:
data = json.loads(data.decode('utf-8'))
print(data)
except Exception:
print("Server: Could not decode message: ", data)
conn.close()
print('Server: client disconnected')
Client:
Here the client attempts to connect to the server with the given ip-addresses
def client(self, ip):
# print(ip)
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
connected = False
while not connected:
try:
print("Client: Connecting to, ", ip)
self.cli.connect((ip, 44445))
connected = True
except Exception:
print('Client: Could not connect to: ', ip, '. Retrying...')
time.sleep(5)
while True:
time.sleep(2)
try:
print("Client: Sending a msg to, ", ip)
self.cli.send(json.dumps({"id": "{PC1}", "height": self.nodes[self.current_leader].node_stats.lastBlockHeight, "latency": self.nodes[self.current_leader].avgLatencyRecords}).encode('utf-8'))
except Exception:
print("Client: Could not send more data to, ", ip)
break
if I understood correctly you want only one server for each (machine / program)? In this case, I think you need a unique port for each server. Or if you want each client to behave like a client / server to communicate with the main server, you can use your client's recv method.
Exemple 1 (send message to server and wait response):
def client(self, ip):
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
connected = False
while not connected:
try:
print("Client: Connecting to, ", ip)
self.cli.connect((ip, 44445))
connected = True
except Exception:
print('Client: Could not connect to: ', ip, '. Retrying...')
time.sleep(5)
while True:
time.sleep(2)
try:
print("Client: Sending a msg to, ", ip)
self.cli.send(json.dumps({"id": "{PC1}", "height": self.nodes[self.current_leader].node_stats.lastBlockHeight, "latency": self.nodes[self.current_leader].avgLatencyRecords}).encode('utf-8'))
except Exception:
print("Client: Could not send more data to, ", ip)
break
# Waiting for server response
response = self.cli.recv(1024)
Now if you want a server message event, you can create a message handler like this (it is not very clean code it is for the example):
def on_message(self, msg):
print(msg)
def message_handle(self):
while True:
# Waiting for server message
msg = self.cli.recv(1024)
# check is message if valid
self.on_message(msg)
def client(self, ip):
# print(ip)
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
connected = False
while not connected:
try:
print("Client: Connecting to, ", ip)
self.cli.connect((ip, 44445))
connected = True
except Exception:
print('Client: Could not connect to: ', ip, '. Retrying...')
time.sleep(5)
# Connection established start message handler
handler = threading.Thread(target=self.message_handle))
handler.start()
while True:
time.sleep(2)
try:
print("Client: Sending a msg to, ", ip)
self.cli.send(json.dumps({"id": "{PC1}", "height": self.nodes[self.current_leader].node_stats.lastBlockHeight, "latency": self.nodes[self.current_leader].avgLatencyRecords}).encode('utf-8'))
except Exception:
print("Client: Could not send more data to, ", ip)
break
In this example, you only had one server and clients on each machine. Then you have to manage the redirection of messages to target clients at the server level (identify the client sending the message and the target clients to address the messages to the right clients).

Server do not response to multiple request from one client

I try to implement a server which only responds to one client at a time and client side. For the client side, I only used one connection and can send multiple requests to server. For the first request, everything goes well. For all the requests after the first one, the client will report error: socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
. I post my server and client code along with the sample test below:
The server part:
import socket
import re
#create server socket. AF_INET-> ipv4. SOCK_STREAM->socket type
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 20000
#bind the socket to localhost and a well-know port
serverSocket.bind((socket.gethostname(), port))
serverSocket.listen(3)
while True:
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
request = clientSocket.recv(1024).decode()
print('Server received', repr(request))
splitRequest = re.split('\<|\>', request)
if splitRequest[0] == 'EXIT':
if len(splitRequest) == 1:
print "Normal exit"
elif len(splitRequest) > 1:
print splitRequest[1]
else:
if splitRequest[0] == 'GET':
fileName = splitRequest[1]
path = 'test_files/' + fileName
try :
with open(path, 'r') as serverFile:
message = serverFile.read()
print message
clientSocket.send(message)
except Exception as e:
message = str(e)
print message
clientSocket.send(message)
elif splitRequest[0] == 'BOUNCE':
message = splitRequest[1]
print message
clientSocket.sendall(message)
clientSocket.close()
The client side:
import socket
import re
def isValidRequest(input):
if re.match('GET\<.+\>', input) or re.match('BOUNCE\<.+\>', input) or input == 'EXIT' or re.match('EXIT\<.+\>', input):
return True
return False
def receiveAll(socket):
BUFF_SIZE = 4096 # 4 KiB
data = ""
while True:
part = socket.recv(BUFF_SIZE)
data += part
if len(part) < BUFF_SIZE:
# either 0 or end of data
break
return data
# create a client socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
# port number
port = 20000
# connection to hostname on the port.
s.connect((host, port))
while True:
request = raw_input()
if isValidRequest(request):
if request == 'EXIT' or re.match('EXIT\<.+\>', request):
s.send(request)
break
else:
s.send(request)
print "after send"
content = receiveAll(s)
print content
else:
print "Invalid request, please enter it again!"
# close client connection
s.close()
I run a test for request the same txt file-"MACD.txt" from server twice. The input in the console is "GET".The print message in the console for client:
*GET<MACD.txt>*
after send
MACD, short for moving average convergence/divergence, is a trading indicator used in technical analysis of stock prices, created by Gerald Appel in the late 1970s.[1] It is supposed to reveal changes in the strength, direction, momentum, and duration of a trend in a stock's price.
*GET<MACD.txt>*
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
after send
The print message in the server part. And you can see server only print message for the first request:
Got a connection from ('192.168.126.1', 60567)
('Server received', "u'GET<MACD.txt>'")
MACD, short for moving average convergence/divergence, is a trading indicator used in technical analysis of stock prices, created by Gerald Appel in the late 1970s.[1] It is supposed to reveal changes in the strength, direction, momentum, and duration of a trend in a stock's price.
I am confused by what I saw since I search the same problem in Stackoverflow and none of them match my case. I also read the document for python socket but still got nothing

Python Persistent HTTP web proxy

My client initially communicates using persistent HTTP with my own server. I am now trying to insert a web proxy in between them, so ideally the proxy will maintain 2 seperate persistent connections, one with the client and one with the server. How can I create a python web proxy that does that? I've only been able to create a non-persistent one so far, how would I expand it to do persistent connections?
Code so far:
def main():
# host and port info.
host = '' # blank for localhost
port = 80
try:
# create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# associate the socket to host and port
s.bind((host, port))
# listenning
s.listen(BACKLOG)
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket:", message
sys.exit(1)
# get the connection from client
while 1:
print "Proxy running..."
conn, client_addr_port = s.accept()
# create a thread to handle request
thread.start_new_thread(proxy_thread, (conn, client_addr_port))
s.close()
def proxy_thread(conn, client_addr_port):
print "received something...creating new thread"
global threadcount
client_addr = client_addr_port[0]
client_port = client_addr_port[1]
# Check if this is an new video flow (assumption now is that 1 client has 1 video flow, and the video does not terminate)
if client_addr not in client_vid_flows:
print "New client detected", client_addr
client_vid_flows[client_addr] = 0 # Expand to save video rate
# ctrl_msg_timer(client_addr) # Start timer that sends a ctrl_msg to the switch at a certain frequency
with lock:
threadcount = threadcount + 1
print "Thread number:", threadcount
# get the request from browser
request_text = conn.recv(MAX_DATA_RECV)
request = HTTPRequest(request_text)
if not request:
sys.exit(1)
if request.error_code:
sys.exit(1)
host = request.headers['host']
port_pos = host.find(":") # find the port pos (if any)
if (port_pos==-1): # default port
webserver = host
port = 80
else: # specific port
webserver = host.split(":")[0]
port = host.split(":")[1]
print "Connect to: %s:%i" % (webserver, port)
try:
# create a socket to connect to the web server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, port))
s.send(request_text) # send request to webserver
while 1:
# receive data from web server
data = s.recv(MAX_DATA_RECV)
print data
if (len(data) > 0):
# send to browser
conn.send(data)
print 'more to send, len(data)={}'.format(len(data))
else:
print 'end of send'
# s.close()
# conn.close()
except socket.error, (value, message):
if s:
s.close()
if conn:
conn.close()
print "Runtime Error:", message
sys.exit(1)
print "--------------------------------"
#********** END PROXY_THREAD ***********
if __name__ == '__main__':
main()
From wireshark, I see that a request packet is being sent to the proxy. However, the proxy is not picking this up.

Python Server send data not working

I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)

Categories

Resources