我想在VDS上制作我的代理服务器,在我的计算机上设置代理,并在最远程的服务器上编写脚本来处理和转发请求。 在将请求转发到网站(例如 google.com 或 youtube.com )的阶段会发生错误,如果您在本地计算机上运行该程序
(127.0.0.0:65432)
,您将得到 error [WinError 10054]
,但如果您在 VDS 上运行它,您将收到错误 [Errno 104] Connection reset by peer
。但是,在这两种情况下,都会从终端资源收到带有 error of 400
的响应。
[local](https://i.sstatic.net/JBODyk2C.png)
import socket
import sys
import threading
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
BUFFER_SIZE = 10000
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(10)
print(f"Подняли сервер на порту: {PORT}")
while True:
try:
conn, addr = s.accept()
d = threading.Thread(target=conn_string, args=(conn, addr))
d.setDaemon(True)
d.start()
except Exception as e:
print(e)
sys.exit(1)
s.close()
def conn_string(conn, addr):
try:
data = conn.recv(BUFFER_SIZE)
#print(f"Connection: {conn}")
server = data.decode("utf-8")
first_line = server.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 = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])
webserver = temp[:port_pos]
decode_data = decode(data)
#print(f"Address: {addr}")
#print(f"Data: {data}")
#print(f"Webserver: {webserver}")
proxy_server(webserver, port, conn, addr, decode_data)
except Exception as e:
print(e)
conn.close()
sys.exit(2)
def decode(data):
return bytes(data)
def get_vpn():
return ("127.0.0.1", 12345)
def proxy_server(url, host_port, conn, addr, decode_data):
print(url, host_port)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(60.0)
client.connect((url, int(host_port)))
client.send(decode_data)
while True:
response = client.recv(BUFFER_SIZE)
print(response.decode('utf-8'))
if len(response.decode('utf-8')) > 0:
conn.send(response)
dar = float(len(response))
dar = float(dar/1024)
dar = f"{dar} KB"
print(f"[*] Requests Done: {addr[0]} => {dar} <=")
else:
break
print(f"Закрыл соединение с {url}")
client.close()
conn.close()
main()
您的代码盲目地将其收到的第一个请求转发到相关服务器。 但这不是 HTTP/HTTPS 的工作方式:它应该只打开到
CONNECT
请求中找到的主机:端口的连接,向其客户端发送 200 OK
响应,然后将来自任何一方的任何内容复制到其他。
此外,源服务器不需要接受
CONNECT
请求。此类请求只能发送给代理。
更多参考RFC 7231,CONNECT 方法。