在使用 Cargo 时,可能会遇到以下网络错误:
error: failed to download from `https://static.crates.io/crates/...`
Caused by:
[6] Couldn't resolve host name (Could not resolve host: static.crates.io)
这通常是由于网络连接或 DNS 解析问题导致的。
mkdir -p ~/.cargo
创建或编辑 ~/.cargo/config.toml 文件:
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
[net]
retry = 2
git-fetch-with-cli = true
cargo clean
cargo run
如果 USTC 镜像不可用,可以尝试其他镜像:
[source.crates-io]
replace-with = 'tuna'
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index"
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
[source.crates-io]
replace-with = 'sjtu'
[source.sjtu]
registry = "https://mirrors.sjtug.sjtu.edu.cn/crates.io-index"
ping crates.io
ping static.crates.io
macOS:
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
Linux:
sudo systemctl restart systemd-resolved
# 或
sudo service networking restart
确保防火墙没有阻止 Cargo 的网络访问。
如果使用代理,需要配置 Cargo:
[http]
proxy = "http://127.0.0.1:8080"
[https]
proxy = "https://127.0.0.1:8080"
配置完成后,可以通过以下命令验证:
# 清理旧的构建缓存
cargo clean
# 重新构建项目
cargo build
# 或直接运行
cargo run
如果看到类似以下输出,说明问题已解决:
Downloading crates ...
Downloaded cfg-if v1.0.3
Downloaded rand_chacha v0.9.0
...
Compiling libc v0.2.176
...
Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.47s
Running `target/debug/guess_number`
~/.cargo/config.toml 是全局配置,影响所有 Rust 项目对于国内用户,推荐使用以下配置:
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
[net]
retry = 2
git-fetch-with-cli = true
[build]
jobs = 4 # 根据 CPU 核心数调整
这个配置提供了:
💡 提示:如果问题持续存在,可以尝试重启网络服务或联系网络管理员检查网络设置。
今天的 Rust 文章,就到这儿。