Tutorial :How can I find an unused port?



Question:

I need to create a brain-dead HTTP server that returns 404s for everything on localhost. Specifically, I have a program under an acceptance test harness which calls out to a server, but for testing I want to save time by skipping that unrelated check.

I have a way to pass in the URL the program uses as part of the test harness, and the test harness (currently) just creates such a server on port 80.

However, a problem appears if more than one test attempts to run at the same time, because each test harness tries to create an HTTP server on port 80, which fails for one of the harnesses.

I'd therefore like to randomize the port and ensure it is available before attempting to create the HTTP server. How can I check if that port is in use?


Solution:1

I'd have thought the answer is obvious: if a socket listen fails, it's not available: choose another. Just listen to the exceptions.


Solution:2

Bind a socket to port 0, the system will pick an available port, between 1024 and 5000 I believe

You can later learn that assigned port with theSocket.LocalEndPoint property.


Solution:3

Why not mock out the request altogether so that you don't actually need a server or a network connection at all?

That would make for a much less brittle test.

Ok, in any case, could you not just generate a random port in some predefined range, and try to set up a server on it? If it is already occupied, an exception should be thrown.


Solution:4

Socket.Select()  

IIRC


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »