如何找到未使用的端口?
我需要创建一个脑死亡的 HTTP 服务器,它对 localhost 上的所有内容都返回 404。具体来说,我在验收测试工具下有一个程序,它调用服务器,但为了测试,我想通过跳过不相关的检查来节省时间。
我有一种方法来传递程序用作测试工具一部分的 URL,并且测试工具(当前)仅在端口 80 上创建这样一个服务器。
但是,如果多个测试尝试在该端口运行,则会出现问题同时,因为每个测试工具都尝试在端口 80 上创建 HTTP 服务器,但其中一个测试工具失败。
因此,我想随机化端口并确保它在尝试创建 HTTP 服务器之前可用。如何检查该端口是否正在使用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将套接字绑定到端口 0,系统将选择一个可用端口,在 1024 到 5000 之间,我相信
您稍后可以通过
Socket.LocalEndPoint
属性了解分配的端口。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.
国际研究委员会
IIRC