HTTPListener is not working on the network

I tried to create a simple HTTP server using System.Net.HTTPListener, but it does not receive connections from other computers on the network. Code example:

class HTTPServer { private HttpListener listener; public HTTPServer() { } public bool Start() { listener = new HttpListener(); listener.Prefixes.Add("http://+:80/"); listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); return true; } private static void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); Console.WriteLine("New request."); HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; byte[] page = Encoding.UTF8.GetBytes("Test"); response.ContentLength64 = page.Length; Stream output = response.OutputStream; output.Write(page, 0, page.Length); output.Close(); } } class Program { static void Main(string[] args) { HTTPServer test = new HTTPServer(); test.Start(); while (true) ; } } 

Is there something wrong with this code, or is there another problem?

I tried to run the application with administrator privileges, but when I go to the IP address of the computer (i.e. 192.168.1.100) on another computer, I never get a request. The server works fine if the request is sent from the same computer on which the application is running (using "localhost", "127.0.0.1" and "192.168.1.100"). Pinging works fine. I also tried nginx and it works great over the network.

I use HTTPListener as a lightweight server to deliver a web page with a Silverlight XAP file with some dynamic init parameters, clientaccesspolicy.xml and a simple mobile HTML page.

+4
source share
2 answers

Firewall

+19
source

I also thought about the firewall first. However, the problem is when my endpoints are:

From the tutorial, I had a code similar to the following

 String[] endpoints = new String[] { "http://localhost:8080/do_something/", // ... }; 

This code only works locally, and only if you use localhost. To be able to use IP, I changed it to

 String[] endpoints = new String[] { "http://127.0.0.1:8080/do_something/", // ... }; 

This time the request by ip-address worked, but the server did not respond to remote requests from another ip. What made me work for me was to use the star (*) instead of localhost and 127.0.0.1, so the following code:

 String[] endpoints = new String[] { "http://*:8080/do_something/", // ... }; 

Just leaving it here if someone stumbles upon this post like me.

0
source

Source: https://habr.com/ru/post/1401779/


All Articles