2025/7/27大约 2 分钟
Unity设置网络代理,python实现代理转发
一、Unity Hub启用网络代理
在Unity Hub的设置中,没有专门的选项来设置网络代理。有时下载安装安卓相关的模块容易报错,例如Android Build Support Download failed: Validation Failed。
此时可以通过bat设置代理并启动Unity Hub,具体脚本如下。请自行修改ip和端口、Unity Hub路径。
@echo off
set HTTP_PROXY=http://127.0.0.1:10807
set HTTPS_PROXY=http://127.0.0.1:10807
REM Set NODE_TLS_REJECT_UNAUTHORIZED=0
start "" "E:\Unity Hub\Unity Hub.exe" " --trace-deprecation"注意Unity Hub只能使用http协议的代理
二、通过python实现其他协议代理转http协议代理
下方代码是将socks协议转成http协议,请自行修改ip和端口。
import socketserver
import socket
import threading
import select
import urllib.parse
import socks
import time
import traceback
SOCKS_HOST = "127.0.0.1"
SOCKS_PORT = 10808
HTTP_HOST = "127.0.0.1"
HTTP_PORT = 10807
# 全局锁,避免多线程输出冲突
print_lock = threading.Lock()
def extract_host_and_port(request, method, url):
    parsed_url = urllib.parse.urlparse(url)
    host = parsed_url.hostname
    port = parsed_url.port
    if host is None:
        headers = request.decode(errors="ignore").split("\r\n")
        for h in headers:
            if h.lower().startswith("host:"):
                host_line = h.split(":", 1)[1].strip()
                if ":" in host_line:
                    host, port = host_line.split(":")
                    port = int(port)
                else:
                    host = host_line
                    port = 80 if method.upper() != "CONNECT" else 443
                break
    if port is None:
        port = 443 if method.upper() == "CONNECT" else 80
    return host, port
def handle_client(client_socket):
    try:
        request = client_socket.recv(4096)
        if not request:
            client_socket.close()
            return
        first_line = request.split(b'\n')[0].decode(errors="ignore")
        method, url, _ = first_line.split()
        host, port = extract_host_and_port(request, method, url)
        s = socks.socksocket()
        s.set_proxy(socks.SOCKS5, SOCKS_HOST, SOCKS_PORT)
        s.connect((host, port))
        if method.upper() == "CONNECT":
            client_socket.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
        else:
            s.sendall(request)
        bytes_sent = 0
        bytes_recv = 0
        start_time = time.time()
        last_report = start_time
        sockets = [client_socket, s]
        while True:
            r, _, _ = select.select(sockets, [], [], 1)
            if not r:
                continue
            for sock in r:
                data = sock.recv(4096)
                if not data:
                    client_socket.close()
                    s.close()
                    return
                if sock is s:
                    client_socket.sendall(data)
                    bytes_recv += len(data)
                else:
                    s.sendall(data)
                    bytes_sent += len(data)
            now = time.time()
            if now - last_report >= 1.0:
                with print_lock:
                    up_speed = bytes_sent / (now - start_time) / 1024
                    down_speed = bytes_recv / (now - start_time) / 1024
                    print(f"[{threading.current_thread().name}] ⬆ {up_speed:.2f} KB/s ⬇ {down_speed:.2f} KB/s")
                last_report = now
    except Exception as e:
        with print_lock:
            print(f"[ERROR] {e}")
            traceback.print_exc()
        try:
            client_socket.close()
        except:
            pass
class ProxyHandler(socketserver.BaseRequestHandler):
    def handle(self):
        handle_client(self.request)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True
if __name__ == "__main__":
    server = ThreadedTCPServer((HTTP_HOST, HTTP_PORT), ProxyHandler)
    print(f"[+] HTTP proxy running at http://{HTTP_HOST}:{HTTP_PORT} -> SOCKS5 {SOCKS_HOST}:{SOCKS_PORT}")
    server.serve_forever()