[英]How can I find an unused port?
I need to create a brain-dead HTTP server that returns 404s for everything on localhost. 我需要创建一个脑死亡的HTTP服务器,为localhost上的所有内容返回404。 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. 我有办法传入程序用作测试工具一部分的URL,测试工具(当前)只是在端口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. 但是,如果多个测试尝试同时运行,则会出现问题,因为每个测试工具都尝试在端口80上创建一个HTTP服务器,该服务器对其中一个线束失败。
I'd therefore like to randomize the port and ensure it is available before attempting to create the HTTP server. 因此,我想在尝试创建HTTP服务器之前随机化端口并确保它可用。 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 将套接字绑定到端口0,系统将选择一个可用端口,我相信在1024和5000之间
You can later learn that assigned port with the Socket.LocalEndPoint
property. 您可以稍后使用
Socket.LocalEndPoint
属性了解分配的端口。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.