user2250152
user2250152

Reputation: 20635

HttpListener is handling only requests for localhost

I'm testing HttpListener based on the doc. My code is very simple. It's a console application running under the admin privilege:

[STAThread]
static void Main( string[] args )
{
    var prefixes = new[] { "http://localhost:8080/", "http://www.contoso.com:8080/index/" };
    HttpListener listener = new HttpListener();
    foreach( string s in prefixes )
    {
        listener.Prefixes.Add( s );
    }
    listener.Start();
    IAsyncResult result = listener.BeginGetContext( new AsyncCallback( ListenerCallback ), listener );
    Console.WriteLine( "Waiting for request to be processed asyncronously." );
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine( "Request processed asyncronously." );
    Console.ReadLine();
    listener.Close();
}

public static void ListenerCallback( IAsyncResult result )
{
    HttpListener listener = (HttpListener)result.AsyncState;
    HttpListenerContext context = listener.EndGetContext( result );
    HttpListenerRequest request = context.Request;
    HttpListenerResponse response = context.Response;
    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes( responseString );
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write( buffer, 0, buffer.Length );
    output.Close();
 }

If I try http://localhost:8080/ in a web browser then the callback ListenerCallback is called and the response string "Hello world!" appears in the browser.

For http://www.contoso.com:8080/index/ the callback is never called and the web request timed out. How can I identify where is the problem? It's a bug in .NET framework or in my code?

Upvotes: 2

Views: 1166

Answers (1)

eglasius
eglasius

Reputation: 36037

One reason is if the ip of www.contoso.com is not a local IP to the computer where you are running the HttpListener on. Usually because the traffic gets somewhere in your network first and is redirected to the computer that runs the HttpListener which is using a private IP address. Check the answers here for more. Don't blindly take wildcard solutions though, as those can have security vulnerabilities depending on your scenario.

Upvotes: 1

Related Questions