HTTPListener not working over network

Stefan picture Stefan · Mar 16, 2012 · Viewed 13.4k times · Source

I tried creating a simple HTTP server using System.Net.HTTPListener, but it doesn't receive connections from other computers in the network. Example code:

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've tried running the application with administrator privileges, but when I browse to the computer's IP address (i.e. 192.168.1.100) on another computer, I never receive the request. The server works fine if the request is sent from the same computer as where the application is running (using "localhost", "127.0.0.1" and "192.168.1.100"). Pinging works fine. I've also tried nginx, and that works perfectly over the network.

I'm using HTTPListener as a lightweight server to deliver a webpage with a Silverlight XAP file with some dynamic init params, clientaccesspolicy.xml and a simple mobile HTML page.

Answer

spender picture spender · Mar 16, 2012

Firewall