【问题标题】:Simple Web Server: The format of the specified network name is invalidSimple Web Server:指定网络名称的格式无效
【发布时间】:2013-10-06 09:47:10
【问题描述】:

我在编写一个简单的 Web 服务器时遇到问题。我需要能够通过 localhost 和 IP 连接到服务器。但是,我在通过 IP 连接时遇到问题。这是我的代码:

private void start_button_Click(object sender, EventArgs e)
    {
        start_button.Text = "Listening...";

        HttpListener server = new HttpListener();

        server.Prefixes.Add("http://201.0.0.10:69/");
        server.Prefixes.Add("http://localhost:69/");

        server.Start();

        while (true)
        {
            HttpListenerContext context = server.GetContext();
            HttpListenerResponse response = context.Response;

            string page = Directory.GetCurrentDirectory() +
                context.Request.Url.LocalPath;

            if (page == string.Empty)
                page = page + "index.html";

            TextReader tr = new StreamReader(page);
            string msg = tr.ReadToEnd();


            byte[] buffer = Encoding.UTF8.GetBytes(msg);

            response.ContentLength64 = buffer.Length;
            Stream st = response.OutputStream;
            st.Write(buffer, 0, buffer.Length);

            context.Response.Close();
        }
    }

我不断收到此错误:指定网络名称的格式无效。

我知道我的问题在于这一点:

server.Prefixes.Add("http://201.0.0.10:69/");

如果我注释掉这一行,我可以通过 localhost 连接。

有人知道我做错了什么吗?


好的,我得到了 IP 地址,但现在我遇到了这行的问题:

if (page == string.Empty)
            page = page + "index.html";

由于某种原因,它没有将 index.html 添加到末尾。

【问题讨论】:

  • 如果您尝试添加与您的任何主机地址都不对应的前缀,则会发生此错误。你的机器真的有201.0.0.10 地址吗?
  • 我的意思是:确保只使用分配给主机的实际 IP 地址。您可以使用System.Net.Dns.GetHostEntry("").AddressList 获取它们。
  • 谢谢!那行得通!我试图使用我的公共 IP 而不是分配给我的计算机的一个。现在我遇到了另一个问题。出于某种原因,将 index.html 添加到 URL 末尾的 if 语句不起作用。
  • 就在if 之前,您将page 设置为CurentDirectory + LocalPath。你怎么期望它是空的?您可以将其更改为 if (context.Request.Url.LocalPath == "/") 之类的内容(如果未输入路径,浏览器会添加正斜杠)。

标签: c# httplistener


【解决方案1】:

对我有用的解决方案是在 applicationhost.config 文件中添加绑定。

This answer 举例说明了绑定信息的位置以及如何手动编辑它。

在您的情况下,以下绑定信息可能会解决您的问题:

<bindings>
 <binding protocol="http" bindingInformation="*:69:localhost" />
 <binding protocol="http" bindingInformation="*:69:201.0.0.10" /> 
</bindings>

【讨论】:

    【解决方案2】:

    除了在application.config 文件中设置绑定外,您可能还需要通过运行以下命令将系统设置为侦听来自特定 IP 地址的 http:

    netsh http add iplisten 201.0.0.10
    

    您可能还需要添加本地主机:

    netsh http add iplisten 127.0.0.1
    

    正如其他答案中提到的,将这些添加到绑定文件中:

     <binding protocol="http" bindingInformation="*:69:201.0.0.10" /> 
     <binding protocol="http" bindingInformation="*:69:localhost" />
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 2021-01-03
      相关资源
      最近更新 更多