July 10, 2025

rust_socks 流量转发

在分享网络时,某些代理客户端限制了只能暴露在 127.0.0.1 (设置为 0.0.0.0 也不行,大概率是bug)

于是就有了下面这个 rust 流量转发程序,程序利用 tokio (优秀的异步运行时框架),将本地(localhost) 7890 暴露到 (0.0.0.0) 7891,方便外部畅享网络

// Cargo.toml 中添加:
// [dependencies]
// tokio = { version = "1", features = ["full"] }
// anyhow = "1.0"
 
use anyhow::Result;
use tokio::{
    io,
    net::{TcpListener, TcpStream},
};
 
#[tokio::main]
async fn main() -> Result<()> {
    // 在所有接口上监听 7891,转发到本地 7890
    let listener = TcpListener::bind("0.0.0.0:7891").await?;
    println!("Forwarding 0.0.0.0:7891 → 127.0.0.1:7890");
 
    loop {
        let (mut inbound, _) = listener.accept().await?;
        tokio::spawn(async move {
            if let Err(e) = tunnel(&mut inbound).await {
                eprintln!("转发出错: {}", e);
            }
        });
    }
}
 
async fn tunnel(inbound: &mut TcpStream) -> Result<()> {
    // 连接本地 SOCKS5 服务
    let mut outbound = TcpStream::connect("127.0.0.1:7890").await?;
    // 使用 copy_bidirectional 协调双向流量和优雅关闭
    io::copy_bidirectional(inbound, &mut outbound).await?;
    Ok(())
}

使用方法

  1. 确保 Cargo.toml 中已添加以下内容:
[dependencies]
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
  1. 将上面代码保存到 src/main.rs。
  2. 运行:
cargo run --release
  1. 此时外部连接到 0.0.0.0:7891 的流量会被转发到本地 127.0.0.1:7890 的 SOCKS5 服务器。