Python 3.x 试图通过套接字获取403错误代码
我有一个python套接字编程任务。其中一项任务是通过阻止包含/的任何URL来防止恶意攻击/ 在下面的代码中,我注释掉了我希望返回403禁止错误的代码行。但当这行代码处于活动状态时,实际上什么都不会发生。我在命令行中使用curl(--path原样)执行代码,以确保/。/不会被剥离(例如,像Chrome那样)。但当这行代码处于活动状态时,命令提示符中不会返回任何内容。如果代码行被注释掉,那么curl返回52个错误代码。但最终我希望返回403错误代码Python 3.x 试图通过套接字获取403错误代码,python-3.x,sockets,Python 3.x,Sockets,我有一个python套接字编程任务。其中一项任务是通过阻止包含/的任何URL来防止恶意攻击/ 在下面的代码中,我注释掉了我希望返回403禁止错误的代码行。但当这行代码处于活动状态时,实际上什么都不会发生。我在命令行中使用curl(--path原样)执行代码,以确保/。/不会被剥离(例如,像Chrome那样)。但当这行代码处于活动状态时,命令提示符中不会返回任何内容。如果代码行被注释掉,那么curl返回52个错误代码。但最终我希望返回403错误代码 while True: print('R
while True:
print('Ready to serve....')
connectionSocket, addr = serverSocket.accept() #Fill in code to get a connection
try:
message = connectionSocket.recv(1024).decode() #Fill in code to read GET request
filename = message.split()[1]
if("/../" in filename): #security code to see if there is a /../ in the filename URL
#connectionSocket.send('HTTP/1.0 403 Forbidden\r\n'.encode()) # Send HTTP header line(s) into socket
connectionSocket.close()
continue;
我的猜测是,当您激活该行时,它将发送403错误并关闭套接字连接。然而,您并没有跳出循环,因此这将在while循环中继续运行,而不会产生任何输出。尝试将
continue
更改为break
while True:
print('Ready to serve....')
connectionSocket, addr = serverSocket.accept() #Fill in code to get a connection
try:
message = connectionSocket.recv(1024).decode() #Fill in code to read GET request
filename = message.split()[1]
if("/../" in filename): #security code to see if there is a /../ in the filename URL
connectionSocket.send('HTTP/1.0 403 Forbidden\r\n'.encode()) # Send HTTP header line(s) into socket
connectionSocket.close()
break;#exits the while loop
CURL返回错误52
当没有来自服务器的响应时,Curl会给出这个错误,因为HTTP不响应任何请求都是错误的。这很有意义,因为在注释掉该行时,您不会通过套接字发送/接收任何内容
#connectionSocket.send('HTTP/1.0 403 Forbidden\r\n'.encode()) # Send HTTP header line(s) into socket
这将不是有效的HTTP响应。您缺少HTTP头末尾的最后一个\r\n
:
connectionSocket.send(b"HTTP/1.0 403 Forbidden\r\n\r\n")
这个问题解决了吗?如果是,请接受答案,以表明问题已经解决。