Binding HttpListener to a free port


B

bughunter

Hi,

When providing the HttpListener with a list of 'prefixes' to respond to
there doesn't appear to be an option for binding to an arbitrary freely
available port, and if there is then there doesn't seem to be a
mechanism for discovering that port by the calling code.

I'm happy to be proven wrong here but given this situation, the obvious
approach now would be to programatically query the OS for a list of
used and/or available ports, and to pick one of the available ones.
This may introduce the problem of a port being allocated in the time
between querying the OS and binding to the port, but I can handle that
exception and keep trying until a successful bind occurs (hopefully!).

Am I going about this the right way? Is there an alternative to
HttpListener? I suppose I could revert to using HttpListener and
perhaps re-using the provided HTTP classes for handling the HTTP
protocol?

Thanks in advance for any help,

Colin Green
 
Ad

Advertisements

K

Kevin Spencer

A listener, by its very nature, must be listening on a known port number.
So, the model allows you to select the port number. Just like IIS does,
which is an HTTP Listener.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
B

bughunter

Kevin said:
A listener, by its very nature, must be listening on a known port number.
So, the model allows you to select the port number. Just like IIS does,
which is an HTTP Listener.
Hi,

Yes but there are situations where you might want to listen on whatever
port happens to be available. In fact the underlying windows sockets
API allows this by accepting a port number of 0 on the bind() function,
it then finds a free port, binds to it and you can then determine what
that port was by examining the updated address structure. As an example
usage the development web server in Visual Studio 2005 also uses this
technique.

Regards,

Colin Green
 
Ad

Advertisements

K

Kevin Spencer

So, how is the client going to know which port to connect to?

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top