在 Ubuntu 上配置 Rust 的网络环境
一 安装与网络连通性检查
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh,完成后执行 source $HOME/.cargo/env 使环境变量生效。为验证网络连通,运行 cargo search reqwest 或 cargo install ripgrep 测试对 crates.io 的访问。若访问缓慢或超时,见下文“镜像与代理”。二 代理配置
export http_proxy=http://your.proxy.server:port 与 export https_proxy=https://your.proxy.server:port。echo 'export http_proxy=http://your.proxy.server:port' >> ~/.bashrc 与 echo 'export https_proxy=https://your.proxy.server:port' >> ~/.bashrc,然后 source ~/.bashrc(zsh 用户使用 ~/.zshrc)。[http]
proxy = "http://your.proxy.server:port"
[https]
proxy = "http://your.proxy.server:port"
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 也可能被部分工具使用,建议同时设置大小写两种变量。三 镜像源加速
export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static 与 export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup 后再执行安装;或将上述两行写入 ~/.bashrc/~/.zshrc 并 source 使其永久生效。[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=sparse 与 export CARGO_HTTP_MULTIPLEXING=false。上述镜像亦可替换为 清华源 等可用镜像。四 编写与运行网络程序
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(())
}
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 服务,适合作为网络功能的最小起点。五 常见问题与排查
export SSL_CERT_DIR=/etc/ssl/certs 或 export SSL_CERT_FILE=/path/to/ca-bundle.crt,或在 reqwest::Client 中配置自定义证书链。/etc/resolv.conf 中的 DNS 配置(如 nameserver 223.5.5.5),或在容器中显式设置 DNS。http://user:pass@host:port 格式;必要时在 ~/.cargo/config 与代码代理中同时配置。ss -tulpen | grep 8080 查找占用进程并释放端口,或更改程序监听端口。