简体   繁体   中英

How can I find an unused port?

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?

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 the Socket.LocalEndPoint property.

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

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.

Socket.Select()

IIRC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM