<p>I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine.  To do so, I would like to create an <code>HttpListener</code> that listens on a port that is:</p>

<ol>
<li>Randomly selected </li>
<li>Currently unused</li>
</ol>

<p>Essentially, what I would like is something like:</p>

<pre><code>mListener = new HttpListener();
mListener.Prefixes.Add("http://*:0/");
mListener.Start();
selectedPort = mListener.Port;
</code></pre>

<p>How can I accomplish this?</p>

How about something like this:
```
```
static List<int> usedPorts = new List<int>();
    static Random r = new Random();

    public HttpListener CreateNewListener()
    {
        HttpListener mListener;
        int newPort = -1;
        while (true)
        {
            mListener = new HttpListener();
            newPort = r.Next(49152, 65535); // IANA suggests the range 49152 to 65535 for dynamic or private ports.
            if (usedPorts.Contains(newPort))
            {
                continue;
            }
            mListener.Prefixes.Add(string.Format("http://*:{0}/", newPort));
            try
            {
                mListener.Start();
            }
            catch
            {
                continue;
            }
            usedPorts.Add(newPort);
            break;
        }

        return mListener;
    }
```
```
I'm not sure how you would find all of the ports that are in use on that machine, but you should get an exception if you try to listen on a port that is already being used, in which case the method will simply pick another port.