views:

59

answers:

4

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?

A: 

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.

Lasse V. Karlsen
It's an acceptance test. The test doesn't have access to the innards of the application under test at all. It runs the application under test with commandline arguments and examines the results. It's not really a brittle problem because the application under test does not care what the response from the server is -- it's only *sending* data. And sending it to the real remote server adds 5s+ time per test, which is annoying when there are hundreds of them.
Billy ONeal
+2  A: 

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

Amadan
A: 
Socket.Select()

IIRC

leppie
+5  A: 

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.

nos
I didnt know that, never needed it, but really good to know :) +1
leppie
Now if only the HTTP library I was using exposed the actual socket....
Billy ONeal
+1 -- this is probably the best answer, but the HTTP library I'm using unfortunately is crap and doesn't expose the socket for me to check this.
Billy ONeal