温馨提示×

如何在 Ubuntu 上配置 Rust 的网络环境

小樊
36
2025-12-30 06:26:59
栏目: 编程语言

在 Ubuntu 上配置 Rust 的网络环境

一 安装与网络连通性检查

  • 安装或更新 Rust 工具链(rustup):执行命令:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh,完成后执行 source $HOME/.cargo/env 使环境变量生效。为验证网络连通,运行 cargo search reqwestcargo install ripgrep 测试对 crates.io 的访问。若访问缓慢或超时,见下文“镜像与代理”。

二 代理配置

  • 终端会话级(临时):export http_proxy=http://your.proxy.server:portexport https_proxy=https://your.proxy.server:port
  • 持久化到 Shell 配置:echo 'export http_proxy=http://your.proxy.server:port' >> ~/.bashrcecho 'export https_proxy=https://your.proxy.server:port' >> ~/.bashrc,然后 source ~/.bashrc(zsh 用户使用 ~/.zshrc)。
  • Cargo 级配置:创建或编辑 ~/.cargo/config,加入:
    [http]
    proxy = "http://your.proxy.server:port"
    
    [https]
    proxy = "http://your.proxy.server:port"
    
  • 库级配置(以 reqwest 为例):在代码中直接设置代理:
    use reqwest::Proxy;
    
    #[tokio::main]
    async fn main() -> Result<(), reqwest::Error> {
        let client = reqwest::Client::builder()
            .proxy(Proxy::all("http://your.proxy.server:port")?)
            .build()?;
        let res = client.get("http://httpbin.org/ip").send().await?;
        println!("Status: {}", res.status());
        Ok(())
    }
    
  • 说明:如代理需要认证,使用 http://user:pass@host:port 格式;某些环境下仅设置 HTTP_PROXY 也可能被部分工具使用,建议同时设置大小写两种变量。

三 镜像源加速

  • 工具链安装镜像(rustup):临时使用 export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-staticexport RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup 后再执行安装;或将上述两行写入 ~/.bashrc/~/.zshrcsource 使其永久生效。
  • crates.io 索引镜像(Cargo):创建或编辑 ~/.cargo/config,示例(使用中科大源):
    [source.crates-io]
    replace-with = 'ustc'
    
    [source.ustc]
    registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
    
    [net]
    git-fetch-with-cli = true
    
    若遇到某些网络环境索引同步问题,可临时关闭稀疏索引并启用 HTTP 多路复用:export CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparseexport CARGO_HTTP_MULTIPLEXING=false。上述镜像亦可替换为 清华源 等可用镜像。

四 编写与运行网络程序

  • 使用 reqwest + tokio 发起 HTTP 请求(异步):
    use reqwest;
    use tokio;
    
    #[tokio::main]
    async fn main() -> Result<(), reqwest::Error> {
        let res = reqwest::get("https://httpbin.org/get").await?;
        println!("Status: {}", res.status());
        Ok(())
    }
    
  • 使用 tokio 编写异步 TCP 回显服务器
    use tokio::net::{TcpListener, TcpStream};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let listener = TcpListener::bind("127.0.0.1:8080").await?;
        println!("Server listening on 127.0.0.1:8080");
        loop {
            let (mut socket, addr) = listener.accept().await?;
            println!("New client connected: {}", addr);
            tokio::spawn(async move {
                let mut buf = [0; 1024];
                loop {
                    match socket.read(&mut buf).await {
                        Ok(0) => return,
                        Ok(n) => {
                            if let Err(e) = socket.write_all(&buf[..n]).await {
                                eprintln!("write error: {}", e);
                                return;
                            }
                        }
                        Err(e) => {
                            eprintln!("read error: {}", e);
                            return;
                        }
                    }
                }
            });
        }
    }
    
  • 运行:在项目目录执行 cargo run。上述示例分别展示了基于 reqwest 的 HTTP 客户端与基于 tokio 的异步 TCP 服务,适合作为网络功能的最小起点。

五 常见问题与排查

  • 证书错误(企业内网/自签 CA):设置 export SSL_CERT_DIR=/etc/ssl/certsexport SSL_CERT_FILE=/path/to/ca-bundle.crt,或在 reqwest::Client 中配置自定义证书链。
  • DNS 解析慢或失败:检查 /etc/resolv.conf 中的 DNS 配置(如 nameserver 223.5.5.5),或在容器中显式设置 DNS。
  • 代理认证失败:确认用户名与密码正确,并使用 http://user:pass@host:port 格式;必要时在 ~/.cargo/config 与代码代理中同时配置。
  • 端口占用:ss -tulpen | grep 8080 查找占用进程并释放端口,或更改程序监听端口。
  • 防火墙/云安全组:在 UFW/iptables 或云平台安全组中放行对应端口(如 8080)。

0