Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "AccessDenied" when trying to use HttpListener? [duplicate]

Win 7 and VS2010 B2. I am trying to write a minimal web server using the built-in HttpListener. However, I keep getting an AccessDenied exception. Here is the code:

    int Run(string[] args) {

        _server = new HttpListener();
        _server.Prefixes.Add("http://*:9669/");
        _server.Start();

        Console.WriteLine("Server bound to: {0}", _server.Prefixes.First());

        _server.BeginGetContext(HandleContext, null);
    }

I could understand the need to run as administrator if I was binding to a system port, but I don't see why my binding to 9669 should require special permissions.

Any ideas?

like image 475
Frank Krueger Avatar asked Jan 01 '10 02:01

Frank Krueger


1 Answers

Thanks to this SO question: Can I listen on a port (using HttpListener or other .NET code) on Vista without requiring administrator priveleges?

I have an answer.

netsh http add urlacl url=http://*:9669/ user=fak listen=yes

Crazy. Here is my revised function:

    int Run(string[] args) {

        var prefix = "http://*:9669/";
        var username = Environment.GetEnvironmentVariable("USERNAME");
        var userdomain = Environment.GetEnvironmentVariable("USERDOMAIN");

        _server = new HttpListener();
        _server.Prefixes.Add(prefix);

        try {
            _server.Start();
        }
        catch (HttpListenerException ex) {
            if (ex.ErrorCode == 5) {
                Console.WriteLine("You need to run the following command:");
                Console.WriteLine("  netsh http add urlacl url={0} user={1}\\{2} listen=yes",
                    prefix, userdomain, username);
                return -1;
            }
            else {
                throw;
            }
        }


        Console.WriteLine("Server bound to: {0}", _server.Prefixes.First());

        _server.BeginGetContext(HandleContext, null);
    }
like image 154
Frank Krueger Avatar answered Nov 06 '22 09:11

Frank Krueger