Simple Web Server: The format of the specified network name is invalid

user2122140 picture user2122140 · Sep 30, 2013 · Viewed 8.1k times · Source

I'm having a problem with a simple web server that I am writing. I need to be able to connect to the server through localhost and IP. However, I am having problems connecting through IP. Here is my code:

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();
        }
    }

I keep getting this error: The format of the specified network name is invalid.

I know my problem lies in this bit:

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

I can connect through localhost if I comment out this line.

Does anyone know what I could be doing wrong?


Okay, I got the IP adress working, but now I'm having a problem with this line:

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

For some reason, it's not adding index.html to the end.

Answer

Jed picture Jed · Jul 1, 2015

The solution that worked for me was to add a binding in the applicationhost.config file.

This answer gives an example of where the binding information is located and how you can manually edit it.

In your case, the following binding info may fix your problem:

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