问题
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.
回答1:
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>
回答2:
As well as setting the bindings in the application.config
file you may need to set your system to listen for http from certain IP addresses by running this command:
netsh http add iplisten 201.0.0.10
You may also need to add localhost:
netsh http add iplisten 127.0.0.1
And as mentioned in other answers add these to the bindings file:
<binding protocol="http" bindingInformation="*:69:201.0.0.10" />
<binding protocol="http" bindingInformation="*:69:localhost" />
来源:https://stackoverflow.com/questions/19095769/simple-web-server-the-format-of-the-specified-network-name-is-invalid