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

如何让Google VM开放外部HTTP连接?C# HttpListener配置问题排查

C# HttpListener在GCP Ubuntu VM上无法绑定外部IP的问题

我正在Ubuntu 22.04的Google Cloud VM实例上搭建一个简单的C# HttpListener,用于监听外部连接。已经安装了dotnet并上传了源码,但在绑定地址时出现错误,无法实现外部访问的目标。

代码示例

Program.cs

using System;
...
public class Program
{
    public const string ADDRESS = "http://VM_EXTERNAL_IP";
    public const int PORT = 80;
    public static Server server;
    static void Main(string[] args)
    {
        server = new Server(ADDRESS, PORT);
    }
}

Server.cs

public class Server
{
    public string address;
    public int port;
    public Server(string address, int port)
    {
        HttpListener httpserver = new HttpListener();
        httpserver.Prefixes.Add(address + ":" + port + "/");

        httpserver.Start();

        Console.WriteLine("Listening on " + address + ":" + port + "/");
        while (httpserver.IsListening)
        {
            HandleHTTPConnections(httpserver);
        }
    }
}

错误信息

在执行httpserver.Prefixes.Add(address + ":" + port + "/");时抛出以下异常:

Unhandled exception. System.Net.HttpListenerException (99): Cannot assign requested address
   at System.Net.HttpEndPointManager.GetEPListener(String host, Int32 port, HttpListener listener, Boolean secure)
   at System.Net.HttpEndPointManager.AddPrefixInternal(String p, HttpListener listener)
   at System.Net.HttpEndPointManager.AddListener(HttpListener listener)

已尝试的方案

  • 使用VM外部IP:ADDRESS = "http://34.118.16.122",触发上述错误
  • 使用VM内部IP:ADDRESS = "http://10.186.0.2",触发相同错误
  • 使用通用地址:ADDRESS = "http://+",提示地址已被其他进程占用
  • 使用localhost:ADDRESS = "http://localhost",无报错但无法接受外部连接
  • 尝试Google Cloud助手提供的SSH端口转发命令sudo ssh -L 80:localhost:22 user@EXTERNAL_IP_ADDRESS,收到"Permission denied"错误,且该操作对HTTP服务无实际帮助
  • 添加GCP防火墙规则,允许任意内部IP的80端口HTTP连接,无效果

请问接下来应该尝试什么解决方法?

内容的提问来源于stack exchange,提问作者Mihai-Ionut FLOARES

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 12:22:32