You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust调用本地Web服务器遇Connection refused问题求助

Rust调用本地Web服务器连接被拒绝问题

问题详情

本地Web服务器运行在127.0.0.1:8000,通过命令行执行以下curl命令均可正常获取响应:

  • curl -XGET http://127.0.0.1:8000/data
  • curl -XGET http://localhost:8000/data

但使用hyper库(尝试reqwest等其他HTTP库结果一致)编写的Rust代码无法连接本地服务器,触发连接被拒绝错误。

代码示例

pub async fn test() -> Result<()> {
    let res = client
        .get(Uri::from_static("http://localhost:8000/data"))
        .await.unwrap();

    println!("status: {}", res.status());

    let buf = hyper::body::to_bytes(res).await.unwrap();

    println!("body: {:?}", buf);
    Ok(())
}

注:知晓应使用?替代unwrap,但编译器不允许返回带双参数的Result类型,故暂时用unwrap。

报错信息

thread 'main' panicked at 'called Result::unwrap() on an Err value: hyper::Error(Connect, ConnectError("tcp connect error", Os { code: 111, kind: ConnectionRefused, message: "Connection refused" }))

该代码可正常调用非本地HTTP地址,但本地服务器连接失败。

排查与解决方向

  • 强制使用IPv4地址:
    把代码中的http://localhost:8000/data替换为http://127.0.0.1:8000/data。部分HTTP库会优先解析localhost到IPv6的::1,若服务器仅监听IPv4的127.0.0.1,就会出现连接拒绝。
  • 检查客户端配置:
    确认hyper客户端是否有特殊配置(如禁用IPv4、启用代理),确保客户端未限制本地连接。
  • 验证服务器监听范围:
    检查服务器是否绑定到0.0.0.0或127.0.0.1,而非仅外部网卡IP(curl能访问则此概率较低)。
  • 排查防火墙/权限:
    临时关闭本地防火墙测试,或确认Rust程序是否拥有网络访问权限。
  • 更新依赖版本:
    检查hyper/reqwest版本是否存在已知本地连接bug,尝试升级至最新稳定版。

内容的提问来源于stack exchange,提问作者Antoine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:10:45