How to find an unused port?

I need to create a dead HTTP server that returns 404s for everything on localhost. In particular, I have a program under the acceptance test harness that is called to the server, but for testing, I want to save time by skipping this unrelated test.

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

However, the problem occurs if several attempts are launched at the same time, because each test harness tries to create an HTTP server on port 80, which does not work for one of the bugs.

Therefore, I would like to randomize the port and make sure it is available before trying to create an HTTP server. How can I check if this port is in use?

+3
source share
4 answers

I would think that the answer is obvious: if the socket is listening, it is unavailable: choose another. Just listen to the exceptions.

+1
source

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

You will find out later that the assigned port has a property Socket.LocalEndPoint.

+11
source

, ?

.

, , ? , .

0
Socket.Select()

IIRC

-1

Source: https://habr.com/ru/post/1758432/


All Articles