简单Web服务器:指定网络名称的格式无效

问题描述 投票:7回答:2

我正在编写一个简单的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。

c# httplistener
2个回答
0
投票

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

This answer给出了绑定信息所在位置以及如何手动编辑它的示例。

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

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

0
投票

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

netsh http add iplisten 201.0.0.10

您可能还需要添加localhost:

netsh http add iplisten 127.0.0.1

并且如其他答案中所述,将这些添加到绑定文件中:

 <binding protocol="http" bindingInformation="*:69:201.0.0.10" /> 
 <binding protocol="http" bindingInformation="*:69:localhost" />
© www.soinside.com 2019 - 2024. All rights reserved.